cookie本地记住密码

1 篇文章 0 订阅

setMaxAge(intexpiry)方法来设置Cookie的有效期。参数expiry以秒为单位,它具有以下含义:

·如果expiry大于零,就指示浏览器在客户端硬盘上保存Cookie的时间为expriy秒。
·如果expiry等于零,就指示浏览器删除当前Cookie。
·如果expiry小于零,就指示浏览器不要把Cookie保存到客户端硬盘。Cookie仅仅存在于当前浏览器进程中,当浏览器进程关闭,Cookie也就消失。

1.登录界面:

<%
    //先读取本地是否保存用户名和密码
    String account = "";
    String pw = "";
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("account")) {
                account = cookie.getValue();
            }
            if (cookie.getName().equals("password")) {
                pw = cookie.getValue();
            }
        }
    }
    System.out.print(account);
    System.out.print(pw);
%>
<form action="login" method="post">
        <img src="./img/loginpage/loginpage.png">
        <table align="center" cellpadding="0" cellspacing="0">
            <tr>
                <td>用户名:</td>
                <td><input type="text" name="account" value="<%=account %>"
                    width=200> <a href="register.jsp">注册账号</a></td>
            </tr>
            <tr>
                <td><br /></td>
            </tr>
            <tr>
                <td>密 码:</td>
                <td><input type="password" name="password" value="<%=pw %>"
                    width=200 /> </td>
            </tr>

        </table>
        <br />
        <div align="center">
            <input type="checkbox" name="rememb" checked="checked" value="yes" />记住密码 <br />
            <input type="submit" value="登录" />
        </div>
    </form>

2.servlet端

String name = request.getParameter("account");
        String pw = request.getParameter("password");
        String rememb = request.getParameter("rememb");
        System.out.println(name);
        System.out.println(pw);
        System.out.println(rememb);
        User u = Login.login(name, pw);
        if (u.getRights() >= 0) {
            Cookie cookie1 = new Cookie("account", u.getAccount());// 建立cookie
            Cookie cookie2 = new Cookie("password", u.getPassword());// 建立cookie
            if (rememb!=null) {
                // 将用户登录的信息保存到本地cookie中,保存一周。
                cookie1.setMaxAge(7 * 24 * 60 * 60);
                cookie2.setMaxAge(7 * 24 * 60 * 60);
            }else {
                //不记住密码时,将本地的记录清除;
                cookie1.setMaxAge(0);
                cookie2.setMaxAge(0);
            }
            response.addCookie(cookie1);// 写入本地
            response.addCookie(cookie2);// 写入本地
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值