使用Cookie记住用户名和密码

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(); }

 

转载于:https://www.cnblogs.com/da-peng/p/5761772.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值