我正在为 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");
}*/
}
}
任何帮助都会很棒。