美文网首页
JSP随记:储存Cookie 和获取Cookie

JSP随记:储存Cookie 和获取Cookie

作者: 梦之志 | 来源:发表于2016-12-28 10:45 被阅读0次

一、储存Cookie:

1、从表单中获取数据: request.getParameter("username")

2、创建Cookie对象: Cookie usernameCookie = new Cookie("username",username);

3.储存Cookie对象: response.addCookie(usernameCookie);

<%    
    request.setCharacterEncoding("utf-8");  //设置编码    
    //首先判断用户是否选择了记住登录状态    
    String[] isUseCookie = request.getParameterValues("isUseCookie");    
    if (isUseCookie !=null && isUseCookie.length > 0){
        //把用户名和密码保存在Cookie对象里面
        String username = URLEncoder .encode(request.getParameter("username"),"utf-8"); 
       //使用URLEncoder 解决无法在Cookie当中保存中文字符串问题
        String password = URLEncoder .encode(request.getParameter("password"),"utf-8");
        Cookie usernameCookie = new Cookie("username",username);
        Cookie passwordCookie = new Cookie("password",password); 
       usernameCookie.setMaxAge(864000); 
       passwordCookie.setMaxAge(864000);
        response.addCookie(usernameCookie); 
       response.addCookie(passwordCookie);
    }else {
        Cookie[] cookies = request.getCookies(); 
       if (cookies!=null && cookies.length>0){
            for (Cookie c:cookies){
                if (c.getName().equals("username") || c.getName().equals("password")){ 
                   c.setMaxAge(0);  //设置Cookie失效
                    response.addCookie(c); //重新保存 
               } 
           }
        }
    }
%>

二、 获取Cookie 信息

1.获取Cookie数据: request.getCookies();

2.遍历获取到的Cookie数组,取到当中的值: c.getValue()

<%
    request.setCharacterEncoding("utf-8"); 
   String username = "";
    String password = "";
    //获取Cookie数据    Cookie[] cookies = request.getCookies();
    //判断Cookie数据是否存在
    if (cookies!=null && cookies.length>0){
        for (Cookie c:cookies){
            //获取用户名
            if (c.getName().equals("username")){
                username = URLDecoder.decode(c.getValue(),"utf-8");
            }
            //获取密码
            if (c.getName().equals("password")){
                password = URLDecoder.decode(c.getValue(),"utf-8");
            }
        }
    }
%>

相关文章

网友评论

      本文标题:JSP随记:储存Cookie 和获取Cookie

      本文链接:https://www.haomeiwen.com/subject/lznsvttx.html