在项目CourseReport中的原始代码(该代码位于StudentServlet(访问路径为/student/*)中,)
Cookie c_studentNo = new Cookie("studentNo", username);
Cookie c_password = new Cookie("password", password);
c_studentNo.setMaxAge(60 * 60 * 24 * 7);//设置cookie存活周期7天
c_password.setMaxAge(60 * 60 * 24 * 7);
response.addCookie(c_studentNo);
response.addCookie(c_password);
原始代码中,没有设置cookie的路径,所以其默认路径为:/CourseReport/student,只有与该路径处于同级或者下级的requestURL才可以访问到这两个c_studentNo,c_password,而我的login.jsp,位于http://localhost:8088/CourseReport/my/begin/login.jsp下,显然不符合这两个cookie的路径限制,所以无法访问到我想要的cookie。
那么,我只需要合理地修改cookie的路径,如/CourseReport/(即项目下所有的请求都能够访问这两个cookie),
修改代码后如下
Cookie c_studentNo = new Cookie("studentNo", username);
Cookie c_password = new Cookie("password", password);
c_studentNo.setMaxAge(60 * 60 * 24 * 7);//设置cookie存活周期7天
c_password.setMaxAge(60 * 60 * 24 * 7);
//若不设置cookie的路径,则默认为当前Servlet的上一层级(此处cookie的默认路径为/CourseReport/student/
//若请求的request的url不在该层级或该层级之下,则无法获取到cookie: c_studentNo和c_password
c_studentNo.setPath(request.getContextPath() + "/");
c_password.setPath(request.getContextPath() + "/");
response.addCookie(c_studentNo);
response.addCookie(c_password);