0

我正在为 OCPJWCD 做准备。我有点卡在 addHeader 和 setHeader 方法上。我确实理解其中的区别,但是当我尝试在代码中实现它并通过 getHeaders() 或 getHeader() 检索值时。它显示值为空。我在这里添加代码。有人可以检查并告诉我,到底出了什么问题。

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * User: Ben
 * Date: 7/14/13
 * Time: 1:51 PM
 * To change this template use File | Settings | File Templates.
 */
public class TestHeaderServlet extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
      throws ServletException, IOException {
    doPost(httpServletRequest,httpServletResponse);
  }


  @Override
  protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
      throws ServletException, IOException {
    httpServletResponse.setContentType("text/html");
    PrintWriter out = httpServletResponse.getWriter();
    httpServletResponse.setHeader("ben","value1");
    /*httpServletResponse.addHeader("ben","value1");
    httpServletResponse.addHeader("ben","value2");
    httpServletResponse.addHeader("ben","value3");
    httpServletResponse.addHeader("ben","value4");*/
    String value = httpServletRequest.getHeader("ben");
    out.println("value is: " + value)    ;
   /* Enumeration<String> enumeration = httpServletRequest.getHeaders("ben");
    while(enumeration.hasMoreElements()) {
      System.out.println("It has elements");

    }*/


  }
}

任何帮助都会很棒。

4

1 回答 1

3

问题是您将标头添加到 中response,并尝试request在同一HTTP 请求-响应周期中从对象中获取该标头。它不起作用,因为request调用此 Servlet 的初始没有此标头。它被添加到response并发送回客户端,您无法从request对象中检索它。如果您需要在 中设置某些response内容并从request对象中检索它,那么您可以使用Cookie

于 2013-07-14T10:35:36.797 回答