javaweb⑦cookie 和session //todo

cookie是一种在客户端保存信息的技术。在servlet中,使用java.servlet.http.Cookie类来封装一个Cookie消息,在HttpServletResponse接口中定义了一个addCookie方法来向浏览器发送Cookie消息(也就是Cookie对象),在HttpServletRequest接口中定义了一个getCookies方法来读取浏览器发送的web服务器的所有cookie消息 SaveCookieresponse.setContentType("text/html;charset=UTF-8");//添加临时Cookie对象PrintWriter out = response.getWriter();//建立超时时间为0的CookieCookie tempCookie = new Cookie("cookie","87654321");cookie.setMaxAge(0);response.addCookie(cookie);String user = request.getParameter("user");  if(user!=null){  //建立永久cookie对象  cookie userCookie = new Cookie("user",user);  userCookie.setMaxAge(60*60*24);  userCookie.setPath("/");  //添加永久cookie对象  response.addCookie(userCookie);}RequestDispatcher readCookie =     getServletContext().getRequestDispatcher("/ReadCookie")readCookie.include(request,response); ReadCookiepublic class ReadCookie extends HttpServlet{  protected Cookie getCookieValue(Cookie[] cookies,String name){    if(cookies !=null){    for(Cookie c :cookies){    if(c.getName().equals(name))    return c;}  }return null;}public void service(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{  response.setContentType("text/html;charset=UTF-8");  PrintWriter out = response.getWriter();//获取临时cookie  Cookie tempCookie =getCookieValue(request.getCookies(),"temp");  if(tempCookie!=null)    out.println("临时Cookie的值"+tempCookie.getValue()+"
");  else    out.println("临时cookie未设置!
");//获取超时时间为0的cookie  Cookie cookie = getCookieValue(request.getCookies(),"cookie");  if(cookie!=null)    out.println("cookie:"+cookie.getValue()+"
");  else    out.println("cookie已经被删除!
");//获取永久cookie  Cookie userCookie = getCookieValue(request.getCookies(),"userCookie");  if(userCookie!=null)    out.println("user:"+userCookie.getValue());  else    out.println("user未设置");}} Session技术session对象用来保存每个用户的用户信息和会话状态。session对象有服务器端自动创建,可以跟踪每个用户的操作状态。用户首次登陆系统是,服务器会自动给用户分配唯一表示的SessionID,可以用来区分开其他用户。相对Cookie,Session是存储在服务器端的会话,相对安全,而且其存储长度限制也比Cookie的存储长度限制扩大了。通过Cookie跟踪Session;(尚不清楚什么原理)//todo通过URL跟踪Session;

相关内容推荐