cookie:数据存在客户端(浏览器),长期储存
session:数据存在服务器,默认保存30分钟
cookie使用方式:
1.创建cookie对象并用response发送
Cookie cookie = new Cookie("username","zs");
response.addCookie(cookie);
2.获取cookie对象并遍历取出需要的数据
Cookie[] cookies = request.getCookies();
遍历并判断数据
3.因为有些服务器不能识别中文,因此如果是中文需要用URL编码之后存储、获取
编码:String value = "张三"; value = URLEncoder.encode(value, "UTF-8");
解码:value = URLDecoder.decode(value,"UTF-8");
1 @WebServlet("/aServlet")//发送cookie 2 public class AServlet extends HttpServlet { 3 @Override 4 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 5 //发送Cookie==>创建并发送 6 7 //创建Cookie对象 8 // Cookie cookie = new Cookie("username","zs"); 9 10 String value = "张三"; 11 //URL编码 12 value = URLEncoder.encode(value, "UTF-8"); 13 System.out.println("存储数据:"+value); 14 //1.创建Cookie对象 15 Cookie cookie = new Cookie("username",value); 16 //设置存活时间 ,1周 7天 17 cookie.setMaxAge(60*60*24*7); 18 //2. 发送Cookie,response 19 response.addCookie(cookie); 20 }
@WebServlet("/bServlet")//获取cookie public class BServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取Cookie //1. 获取Cookie数组 Cookie[] cookies = request.getCookies(); //2. 遍历数组 for (Cookie cookie : cookies) { //3. 获取数据 String name = cookie.getName(); if("username".equals(name)){ String value = cookie.getValue(); //URL解码 value = URLDecoder.decode(value,"UTF-8"); System.out.println(name+":"+value); break; } } }
session使用方式:
1.存储数据(获取session对象,使用set方法存储)
HttpSession session = request.getSession();
session.setAttribute("String",Object);
2.获取数据
Object o = session.getAttribute(key);
3.注意事项
(1) session默认存储30分钟
(2) 利用session.invalidate();方法销毁session
@WebServlet("/demo1")//存储session public class SessionDemo1 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //存储到Session中 //1. 获取Session对象 HttpSession session = request.getSession(); System.out.println(session); //2. 存储数据 session.setAttribute("username","zs"); }
@WebServlet("/demo2")//获取session public class SessionDemo2 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取数据,从session中 //1. 获取Session对象 HttpSession session = request.getSession(); System.out.println(session); //2. 获取数据 Object username = session.getAttribute("username"); System.out.println(username); // 销毁 session.invalidate(); }
标签:方式,request,value,session,Cookie,cookie,response From: https://www.cnblogs.com/changeyi/p/16972390.html