关于Session和Cookie 这里就不细说了,直接上代码说明网站中的"记住我"checkbox的应用
第一个Servlet
public class cookieServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String name = (String) request.getSession().getAttribute("userName"); if(name!=null&&!name.trim().equals("")){ out.print("欢迎你"+name); }else{ out.print("请登陆"); } System.out.println(request.getSession().getId()+"------get请求"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String checked = request.getParameter("me"); if(checked!=null){ Cookie ck = new Cookie("JSESSIONID",request.getSession().getId()) ck.setMaxAge(60*30); ck.setPath("/"); response.addCookie(ck); } String userName = request.getParameter("userName"); if(userName!=null&&!userName.trim().equals("")){ request.getSession().setAttribute("userName", userName); } //doGet(request, response); //禁用cookie url重写 //form 请求 但一共是两次请求 dopost中的session和doget中的session不是同 一个了已经 //response.sendRedirect(request.getContextPath()+"/cookieServlet"); System.out.println(request.getSession().getId()+"------post请求"); //url 重写 String url = response.encodeRedirectURL(request.getContextPath()+"/cookie Servlet"); response.sendRedirect(url); }}
第二个Servlet
package com.test.cookie;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class TestCookieServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String name = (String) request.getSession().getAttribute("userName"); if(name!=null&&!name.trim().equals("")){ out.print("你是"+name+"-----TestCookieServlet"); }else{ out.print("你是没有名字-----TestCookieServlet"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); }}
一个jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%=basePath%>"> My JSP 'index.jsp' starting page
说明
1 正常情况下浏览器cookie是开启的,但是万一被禁用这里暂时使用了url重写 的方式解决,当然还有其它的方式。
2 个人测试的时候(火狐)即使禁用了cookie但还是可以正常访问,后来通过 firebug发现,cookie选项上选择禁用localhost的cookie就可以了。
3 这里关于cookie的配置,api就可以了都是有的而且解释很清楚。