闲来无事打算写个servlet,myeclipse自动生成了下面的代码:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
String userName = request.getParameter("username");
System.out.println("the name you get is :" + userName);
Cookie cookie = new Cookie("userName", userName);
response.addCookie(cookie);
}
再添上我想做的事情:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
String userName = request.getParameter("username");
System.out.println("the name you get is :" + userName);
Cookie cookie = new Cookie("userName", userName);
response.addCookie(cookie);
}
测试居然没有任何效果,cookie没有设置上。经过反复研究发现把这几句提前到flush()方法之前就好使了。仔细想想其中的原因,应该是这样的:
1.cookie必须随response的头信息传递,否则是无效的;
2.out对象是缓存的,所以response中设置cookie可以放在out.println(XXXXX)方法的后面;
3.调用flush()方法时候,将信息发送回浏览器,在这之前如何设置了cookie,则response会将这个信息放置在头信息中返回,浏览器收到后就存下来了;
4.如果将设置cookie的代码放在flush之后,因为信息已经发走了,所以无法再在头信息中设置值了。所以就无效了。
5.不过,flush之后仍可以向前台页面传送东西,这个是没问题的。
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.flush();
out.println("<div> 1234567890 </div>");
out.println(" </BODY>");
out.println("</HTML>");
out.close();
}
这样获取的页面是完整的,显示没有任何问题。