标签:servlet httpservlet java cookie javaee
(1)如何创建cookie案例
package com.tsinghua; import javax.servlet.http.*; import java.io.*; public class CookieTest1 extends HttpServlet{ //处理get请求 public void doGet(HttpServletRequest req,HttpServletResponse res){ try { res.setContentType("text/html;charset=gbk"); PrintWriter pw=res.getWriter(); //当用户访问该servlet时, 就将信息创建到该用户的cookie中 //1. 现在服务器端创建一个cookie Cookie myCookie=new Cookie("color1","red"); //2. 该cookie存在的时间 以秒为单位 myCookie.setMaxAge(30000); //如果你不设置存在时间,那么该cookie将不会保存 //3. 将该cookie写回到客户端 res.addCookie(myCookie); pw.println("已经创建了cookie"); } catch (Exception ex) { ex.printStackTrace(); } } }
package com.tsinghua; import javax.servlet.http.*; import java.io.*; public class CookieTest2 extends HttpServlet{ //处理get请求 public void doGet(HttpServletRequest req,HttpServletResponse res){ try { res.setContentType("text/html;charset=gbk"); PrintWriter pw=res.getWriter(); //从客户端得到所有cookie信息 Cookie [] allCookies=req.getCookies(); int i=0; //如果allCookies不为空... if(allCookies!=null){ //从中取出cookie for(i=0;i<allCookies.length;i++){ //依次取出 Cookie temp=allCookies[i]; if(temp.getName().equals("color1")){ //得到cookie的值 String val=temp.getValue(); pw.println ("color1="+val); break; } } if(allCookies.length==i){ pw.println("cookie 过期"); } }else{ pw.println ("不存在color1这个cookie/或是过期了!"); } } catch (Exception ex) { ex.printStackTrace(); } } }
package com.tsinghua; import javax.servlet.http.*; import java.io.*; public class CookieTest3 extends HttpServlet{ //处理get请求 public void doGet(HttpServletRequest req,HttpServletResponse res){ try { res.setContentType("text/html;charset=gbk"); PrintWriter pw=res.getWriter(); //从客户端得到所有cookie信息 Cookie [] allCookies=req.getCookies(); int i=0; //如果allCookies不为空... if(allCookies!=null){ //从中取出cookie for(i=0;i<allCookies.length;i++){ //依次取出 Cookie temp=allCookies[i]; if(temp.getName().equals("color")){ //将该cookie删除 temp.setMaxAge(0); pw.println("删除了color这个cookie"); break; } } } } catch (Exception ex) { ex.printStackTrace(); } } }
标签:servlet httpservlet java cookie javaee
原文地址:http://blog.csdn.net/xlgen157387/article/details/38960483