码迷,mamicode.com
首页 > 其他好文 > 详细

6 Cookies 和Session

时间:2018-02-12 13:43:50      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:string   extends   服务   rem   date   ++   i++   move   取数据   

1.HTTP协议无状态带来的问题

   http协议在一个会话中的多个请求之间是不能共享数据的
   (实际是需要在一个会话的多个请求共享数据)
   会话跟踪技术:在一个会话共享数据

2.解决一个会话中多个请求之间共享数据的三种方式

   ①.使用GET方式,将需要共享的数据以参数的形式传递给下一个页面即可
     使用GET方式共享数据,所有数据都暴露在地址栏中,不安全
     ②使用cookie技术
     将需要共享的数据封装到浏览器的请求头中
         ③使用session技术

3.Cookie

    客户端技术,将需要共享的数据存放在浏览器中,每次请求时,对应需要共享数据的
    页面只需在浏览器获取需要的数据即可。
      ①创建Cookie对象共享数据
        Cookie cookie=new Cookie(String name,String value);
      ②将cookie响应给浏览器
         resp.addCookie(cookie);
       ③从请求对象获取所有的cookie
        Cookie[] cookies=req.getCookies();
    for(Cookie cookie:cookies){
       if("currentName".equals(cookie.getName())){
         String username=cookie.getValue();
       }
    }
   4.cookie中文问题的解决方案,先编码后解码

      编码:
     Cookie cookie=new Cookie("currentName",URLEncoder.encode(username,"utf-8"));
  解码:
     username=URLDecoder.decode(cookie.getValue(),"utf-8");

Cookie的缺陷:
    Cookie不能存储中文字符
Cookie一次只能存储单个字符串,不能存储对象
cookie大小限制在4kb内
cookie数据是存储在浏览器中的,浏览器把Cookie数据删除了,那么共享数据就找不回来了

     不同Cookie下面的路径是不同的,路径不同的Cookie之间是不能共享数据的
 解决方案: 将Cookie路径设置项目的根路径  
         cookie.setPath(“/”)
 @WebServlet("/cookie/login")
 public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");
    resp.setContentType("text/html;charset=utf-8");

    //接受请求参数
    String username = req.getParameter("username");
    //================================================
    //创建Cookie对象,并且共享数据 (相当办卡的操作)
    Cookie cookie = new Cookie("currentName", URLEncoder.encode(username,"utf-8"));
    //设置Cookie的时长 单位 秒
    //cookie.setMaxAge(10);
    //删除Cookie 
    //cookie.setMaxAge(0);
    //设置Cookie的路径为根路径
    cookie.setPath("/");
    //将Cookie数据响应给浏览器 (相当于将办理好的会员卡给用户)
    resp.addCookie(cookie);
    //创建新的Cookie ,覆盖之前的cookie (相当于修改了cookie)

// Cookie cookie1 = new Cookie("currentName", "jinken");
// resp.addCookie(cookie1);

    //================================================

    PrintWriter out = resp.getWriter();
    out.print("欢迎 : "+username+" <br>");
    out.print("<a href=‘/ooxx/list‘>收件箱(500)</a>");
}

}

 @WebServlet("/ooxx/list")
public class ListServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");
    resp.setContentType("text/html;charset=utf-8");

    // =============================================
    String username = null;
    // 从请求对象中获取所有的cookie
    Cookie[] cookies = req.getCookies();
    for (Cookie cookie : cookies) {
        if("currentName".equals(cookie.getName())){
            username = URLDecoder.decode(cookie.getValue(), "utf-8");
            break;
        }
    }

    // =============================================

    PrintWriter out = resp.getWriter();
    out.print("欢迎 :"+username+" <br>");
    for (int i = 0; i < 5; i++) {
        out.print("<a href=‘/cookie/content‘>邮件 (" + i + ")</a><br/>");
    }
}

}

@WebServlet("/cookie/content")
public class ContentServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");
    resp.setContentType("text/html;charset=utf-8");
    String username = null;
    // =============================================
    Cookie[] cookies = req.getCookies();
    for (Cookie cookie : cookies) {
        if("currentName".equals(cookie.getName())){
            username = URLDecoder.decode(cookie.getValue(), "utf-8");
        }
    }
    // =============================================
    PrintWriter out = resp.getWriter();
    out.print("欢迎 : "+username+" <br>");
    out.print("班长, 你最近好吗?");

}

}

jsp中书写Cookies
<%   
    Cookie cookie = new Cookie(   
            URLEncoder.encode("姓名","UTF-8"),   
            URLEncoder.encode("李佳龙","UTF-8")   
    );   
    response.addCookie(cookie);   
%>   
<html>   
<title>Cookie-中文</title>   
<body>   
<%   
    if(request.getCookies()!=null)   
    {   
        for(Cookie coo : request.getCookies())   
        {   
            String name =URLDecoder.decode(coo.getName(),"UTF-8");   
            String value = URLDecoder.decode(coo.getValue(),"UTF-8");   
            out.println(name "-- " value);   
        }   
    }   
%>    
el表达式:

${cookie}<!-- 显示所有Cookie对象 -->   
${cookie.age.name }<!-- 显示Cookie名为age的name -->   
${cookie.age.value }<!-- 显示Cookie名为age的值 -->  
4.Session
       Session是服务器端技术(把识别数据/共享数据存放在服务端)
       为每一个用户的浏览器创建独立的session,可以把数据存放在各自的session中,
       取数据也从各自session取
       (session是一个特殊的cookie,session得底层依然是cookie技术,cookie是内存地址
          JSESSIONID)
       1.获取Session对象
          HttpSession session=request.getSession();
      如果内存中有session对象,返回,没有则创建一个并返回
       2.共享数据
            setAttribute("USER_IN_SESSION",user);
       3.获取共享数据
           getAttribute("USER_IN_SESSION");

   当cookie被禁用后,URL重写问题
         浏览器禁用cookie后,就再也不能接收服务器响应的cookie,此时cookie和session
     就不能共享数据,直接访问URL地址是不能获取共享数据的
        使用URL重写
        resp.encodeURL(String url);
        如果浏览器禁用cookie,url会自动加上jsessionid,如果没有禁用,就不会
        加上jsessionid

@WebServlet("/session/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //接受请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        //================================================
        //1.获取Sesion对象
        HttpSession session = req.getSession();
        //2.将数据共享的Session对象中
        //session.setAttribute("USERNAME_IN_SESSION", username);
        session.setAttribute("USER_IN_SESSION", user);
        //3.修改共享数据
        //session.setAttribute("USERNAME_IN_SESSION", "虚竹");
        //4.删除session中共享的数据
        //session.removeAttribute("USERNAME_IN_SESSION");
        //5.清空Sesion对象中所有数据
        //session.invalidate();
        //6.设置当前Session10秒钟超时
        //session.setMaxInactiveInterval(10);
        //获取Session的id
        String sessionId = session.getId();
        System.out.println(sessionId);
        //================================================
        //使用url重写
        //String newUrl = resp.encodeURL(String oldUrl);
        // 如果浏览器禁用了 Cookie,newUrl后面会自动加上 jsessionid,如果没有禁用,就不会加上jsession
        PrintWriter out = resp.getWriter();
        out.print("欢迎 : "+username+" <br>");
//      out.print("<a href=‘/session/list;jsessionid="+session.getId()+"‘>收件箱(500)</a>");
        out.print("<a href=‘"+resp.encodeURL("/session/list")+"‘>收件箱(500)</a>");
    }

}

@WebServlet("/session/list")
public class ListServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        // =============================================
        //获取Session对象
        HttpSession session = req.getSession();
        //获取sesion共享的数据
        User user = (User)session.getAttribute("USER_IN_SESSION");
        System.out.println(user);
        // =============================================

        PrintWriter out = resp.getWriter();
        out.print("欢迎 :"+user.getUsername()+" <br>");
        for (int i = 0; i < 5; i++) {
            //out.print("<a href=‘/session/content;jsessionid="+session.getId()+"‘>邮件 (" + i + ")</a><br/>");
            out.print("<a href=‘"+resp.encodeURL("/session/content")+"‘>邮件 (" + i + ")</a><br/>");
        }
    }

}
@WebServlet("/session/content")
public class ContentServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");
    resp.setContentType("text/html;charset=utf-8");
    // =============================================
    // 获取Session对象
    HttpSession session = req.getSession();
    // 获取sesion共享的数据
    User user = (User) session.getAttribute("USER_IN_SESSION");
    // =============================================
    PrintWriter out = resp.getWriter();
    out.print("欢迎 : " + user.getUsername() + " <br>");
    out.print("班长, 你最近好吗?");

}

}

6 Cookies 和Session

标签:string   extends   服务   rem   date   ++   i++   move   取数据   

原文地址:http://blog.51cto.com/10913595/2071301

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!