问个关于JSP与Servlet读取写入Cookie的问题,十分费解,忘高手指教!谢谢!jsp页面的代码如下:<%@ page language="java" import="javax.servlet.http.Cookie" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%
boolean isName = false;
boolean isPwd = false; Cookie[] cookies = request.getCookies();

for (int i = 0; i < cookies.length; i++){
Cookie cookie = cookies[i];

if (cookie.getName().equals("username")){
isName = true;
}

if (cookie.getName().equals("password")){
isPwd = true;
}

if (isName && isPwd){
break;
}
}

if (isName && isPwd){
System.out.print("存在该Cookie");
}else{
System.out.print("没有该Cookie");
//Cookie cookieusername = new Cookie("username", "a");
//Cookie cookiepassword = new Cookie("password", "a");

//cookieusername.setMaxAge(60);
//cookiepassword.setMaxAge(60);

//response.addCookie(cookieusername);
//response.addCookie(cookiepassword);
}
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
  </head>
  
  <body>
    <h1>测试页面</h1>
    
    <form method="POST" action="servlet/CookieServlet">
     <input type="submit" value="确定"/>
    </form>
  </body>
</html>
Servlet的代码(缩短版面只把doPost方法写出来):public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

request.setCharacterEncoding("GBK");
response.setContentType("text/html");
response.setCharacterEncoding("GBK");

Cookie cookieusername = new Cookie("username", "a");
Cookie cookiepassword = new Cookie("password", "a");

cookieusername.setMaxAge(60);
cookiepassword.setMaxAge(60);

response.addCookie(cookieusername);
response.addCookie(cookiepassword);
}大家应该看到我在JSP页面的Scriptlet里面注释掉了写入Cookie的代码,这就是问题所在,我第一次进入JSP页面显示没有该Cookie(正常),刷新后显示存在该Cookie(也正常),后来我想通过提交表单,进Servlet里面写入试验下,所以注释掉这段代码,原封不动的复制到Servlet里面,按理说点击确定进入Servlet里面执行写入Cookie代码后,我再打开JSP页面应该显示存在该Cookie,但不管我怎么刷新都显示没有该Cookie(我已经提交过表单,在Servlet里面设置断点调试也确定写入了Cookie)!这是为什么?忘这里的高手能告诉我问题所在!谢谢了先!

解决方案 »

  1.   

    1 用 firefox + firebug 看看2 cookieusername.setPath("/"); // 增加这一个看看
      

  2.   

    十分感谢楼上的答复,在Servlet里面写入Cookie时加入setPath("/")方法的确正常了,等下就结帖给分,麻烦能问下是为什么吗?
      

  3.   

    知道了,原来在Servlet下写入的cookie,在JSP里面是读取不到的,path默认是产生cookie的路径。设置setPath("/")目的就是让设置的Cookie在同一应用服务器内共享!希望能帮到和我一样问题的朋友!