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

使用Cookie记住用户名和密码

时间:2016-08-11 17:55:50      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

Login.jsp

<form name = "f1" method="get" action="servlet/LoginServlet">
    <table>
        <tr>
            <td>Username:</td>
            <td><input type="text" name="username" value="${un}"></td>
        </tr>
        <tr>
            <td>Password:</td>
            <td><input type="password" name = "password" value="${pw}"></td>
        </tr>
        <tr>
            <td>AutoLogin:</td>
            <td><input type="checkbox" name = "auto" value = "1"></td>
        </tr>    
        <tr>
            <td colspan="2" align="center"><input type="submit" value="Login"> </td>
        </tr>
    </table>
    
    </form>

PrepareLogin

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cs = request.getCookies();
        
        
        if(cs!=null && cs.length>0){
            for(int i = 0 ; i < cs.length ; i++){
                Cookie c = cs[i];
                System.out.println(cs.length);
                System.out.println(i+"--"+cs[i].getName());
                if(c.getName().equals("username")){                    
                    String value = c.getValue();
                    request.setAttribute("un", value);
                    System.out.println(value);
                }
                if(c.getName().equals("password")){
                    String value = c.getValue() ;
                    request.setAttribute("pw", value);    //将值传递给jsp页面
                    System.out.println(value);
                }
            }
        }
        
        request.getRequestDispatcher("/login.jsp").forward(request, response);
    }
保存Cookie

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String auto = request.getParameter("auto"); String username = request.getParameter("username"); String password = request.getParameter("password"); if(auto != null && auto.equals("1")){ Cookie u = new Cookie("username", username); Cookie p = new Cookie("password",password); u.setMaxAge(60*60); p.setMaxAge(60*60); response.addCookie(u); response.addCookie(p); } PrintWriter w = response.getWriter(); w.println("
<html>"+ "Hello"+ "</html>" ); w.flush(); w.close(); }

 

使用Cookie记住用户名和密码

标签:

原文地址:http://www.cnblogs.com/da-peng/p/5761772.html

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