我正在为OCPJWCD做准备。我有点卡在addHeader和setHeader方法上。我做 理解差异,但当我试图在代码中实现它并检索 值通过getHeaders()或getHeader()。它将值显示为null。我补充说 这里的代码。有人可以检查并让我知道,到底出了什么问题。
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");
}*/
}
}
任何帮助都会很棒。
答案 0 :(得分:3)
问题是您要将标头添加到response
,并尝试从同一 HTTP请求 - 响应周期中的request
对象中获取该标头。它不起作用,因为调用此Servlet的初始request
没有此标头。它会被添加到response
并发送回客户端,您无法从request
对象中检索回来。如果您需要在response
中设置内容并从request
对象中检索回来,则可以使用Cookie。