CRM-登录功能回车登录和记住密码

接上一篇:CRM-登录功能实现

1. 实现回车登录

  1. 回顾以下jquery事件函数的用法:
选择器.click(function(){
//js代码
})

上述用法表示给指定元素添加点击事件

选择器.click();

上述用法表示在指定元素上模拟发生一次点击事件

所以实现按下回车键登录,就是按键后模拟登录按钮的点击事件,
直接在script标签中添加代码如下

  //给整个浏览器窗口添加键盘按下事件
        $(window).keydown(function (e) {
            //回车键的keyCode是13
            if(e.keyCode==13){
                $("#loginBtn").click();
            }
        })

2. 记住用户名和密码

在这里插入图片描述

  1. 用户第一次选中Remember me,记住用户名和密码,第二次访问时自动填写

  2. 第二次访问时选中Remember me,记住用户名和密码,第三层访问时自动填写,第二次访问时没有选中Remember me,不记住密码,把上次保存的数据删除

  3. 在UserController.java类中的login()方法中添加参数HttpServletResponse response

  4. 在登录成功的判断语句中添加判断isRemPwd属性值是否为true。(checkbox的属性值为true/false)

2.1 UserController页面添加代码

if("true".equals(isRemPwd)){
    Cookie cookie = new Cookie("loginAct", loginAct);
	cookie.setMaxAge(10*24*60*60);
	response.addCookie(cookie);
	Cookie cookie2 = new Cookie("loginPwd", loginPwd);
	cookie2.setMaxAge(10*24*60*60);
 	response.addCookie(cookie2);
}else {
    Cookie cookie3 = new Cookie("loginAct", "1");
    cookie3.setMaxAge(0);
    response.addCookie(cookie3);
    Cookie cookie4 = new Cookie("loginPwd", "0");
	cookie4.setMaxAge(0);
    response.addCookie(cookie4);
}

2.2 如何把UserController的cookie显示到jsp页面?

以前我们在java中获取cookie

response.addCookie(cookie4);
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
	if(cookie.getName()=="loginAct"){
		String loginAct = cookie.getValue();
	}else if(cookie.getName()=="loginPwd"){
		String loginPwd = cookie.getValue();
	 }
}

现在把 login.jsp页面的input标签的value值直接填写为

value="${cookie.loginAct.value}"
value="${cookie.loginPwd.value}"

如上就可以获取cookie值,上面的.value就是调用getValue()方法
在这里插入图片描述

3. 完整代码

3.1 login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
%>
<html lang="en">
<head>
    <base href="<%=basePath%>">
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="jquery/bootstrap-3.4.1/dist/css/bootstrap.min.css"/>

    <script type="text/javascript" src="jquery/jquery-3.5.1.js"></script>
    <script type="text/javascript" src="jquery/bootstrap-3.4.1/dist/js/bootstrap.min.js"></script>
    <script type="text/javascript">
        //给整个浏览器窗口添加键盘按下事件
        $(window).keydown(function (e) {
            //回车键的keyCode是13
            if(e.keyCode==13){
                $("#loginBtn").click();
            }
        })
        $(function () {
            $("#loginBtn").click(function () {
                //trim()去除空格
                let loginAct1 = $.trim($("#loginAct").val());
                let loginPwd1 = $.trim($("#loginPwd").val());
                //attr获取属性值,获取不到值是true或者false的属性值,例如checkbox,selected,readonly,disabled
                // $("#isRemPwd").attr("")
                //prop()专门用来获取值是true或者false的函数
                let isRemPwd1 = $("#isRemPwd").prop("checked")
                //表单数据
                if (loginAct1 == "" || loginPwd1 == "") {
                    alert("Username or Password can't be null!!");
                    return;
                }
                $.ajax({
                    url: "settings/qx/user/login.do",
                    data: {
                        loginAct: loginAct1,
                        loginPwd: loginPwd1,
                        isRemPwd: isRemPwd1
                    },
                    type: "post",
                    dataType: "json",
                    success: function (ret) {
                        if (ret.code == "1") {
                            window.location.href = "/workbench/index.do";//跳转到controller,不能直接跳转到静态页面
                        } else {
                            $("#msg").html(ret.message);
                        }
                    },
                    beforeSend: function () {//当ajax向后台发送请求之前,会自动执行本函数该函数的返回值能够决定ajax是否真正向后台发送请求:
                        //如果该函数返回true,则ajax会正在向后台发送请求,否则,如果该函数返回false则ajax放弃向后台发送请求
                        $("#msg").text("正在努力验证....");
                        return true;

                    }
                })

            });
        })
    </script>
</head>
<body>
<div style="position: relative;background-color: black">
    <img src="image/xanadu.jpg" style="width: 50%;height: 100%;">
    <div style="position:absolute;top:10px;right:5px;width: 50%;float: right;">
        <div class="modal-dialog" role="document" style="width: 80%;">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">登录</h4>
                </div>
                <form class="form-horizontal">
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="inputEmail3" class="col-sm-2 control-label">Username</label>
                            <div class="col-sm-10">
                                <input id="loginAct" name="loginAct" value="${cookie.loginAct.value}" type="text" class="form-control" id="inputEmail3"
                                       placeholder="Username">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="inputPassword3" class="col-sm-2 control-label">Password</label>
                            <div class="col-sm-10">
                                <input id="loginPwd" value="${cookie.loginPwd.value}" name="loginPwd" type="password" class="form-control"
                                       id="inputPassword3" placeholder="Password">
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <div class="checkbox">
                                    <label>
                                        <input id="isRemPwd" name="isRemPwd" type="checkbox"> Remember me
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <button id="loginBtn" type="button" class="btn btn-default">Login in
                                </button>
                            </div>
                        </div>
                        <div><span style="color: red" id="msg"></span></div>

                    </div>
                </form>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->


    </div>
</div>
</body>
</html>

3.2 UserController

package com.lyx.settings.web.controller;


import com.lyx.commons.contants.Contants;
import com.lyx.commons.domain.ReturnObject;
import com.lyx.settings.domain.User;
import com.lyx.settings.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/settings/qx/user/toLogin.do")
    public String toLogin() {
        return "settings/qx/user/login";
    }

    @RequestMapping("/settings/qx/user/login.do")
    public @ResponseBody Object login(String loginAct, String loginPwd, String isRemPwd, HttpServletResponse response, HttpServletRequest request) {
        //封装参数
        Map<String, Object> map = new HashMap<>();
        map.put("LoginAct", loginAct);
        map.put("LoginPwd", loginPwd);
        //调用service层方法
        User user = userService.queryUserByLoginActAndPwd(map);
        ReturnObject returnObject = new ReturnObject();
        if (user == null) {
            //登录失败,用户名或密码错误
            returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("用户名或密码错误");
        } else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = simpleDateFormat.format(new Date());
            if (format.compareTo(user.getuExpireTime()) > 0) {
                //登录失败,账号已经过期了
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("账号已过期");
            } else if ("0".equals(user.getuLockState())) {
                //登录失败,状态被锁定
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("状态被锁定");
            } else if(!user.getuAllowIps().contains(request.getRemoteAddr())){
                //判断当前用户的ip地址是不是包含在数据库表里的u_allow_ips
               //不包含,登录失败,ip受限制
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("ip受限制");
            }else{
                returnObject.setCode(Contants.RETURN_OBJECT_CODE_SUCCESS);
                //把user保存到session作用域中
                HttpSession session = request.getSession();
                session.setAttribute(Contants.SESSION_USER,user);
                //
                if("true".equals(isRemPwd)){
                    Cookie cookie = new Cookie("loginAct", loginAct);
                    cookie.setMaxAge(10*24*60*60);
                    response.addCookie(cookie);
                    Cookie cookie2 = new Cookie("loginPwd", loginPwd);
                    cookie2.setMaxAge(10*24*60*60);
                    response.addCookie(cookie2);
                }else {
                    Cookie cookie3 = new Cookie("loginAct", "1");
                    cookie3.setMaxAge(0);
                    response.addCookie(cookie3);
                    Cookie cookie4 = new Cookie("loginPwd", "0");
                    cookie4.setMaxAge(0);
                    response.addCookie(cookie4);
                }
            }
        }
        return returnObject;
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

素心如月桠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值