文章目录

前言

本文展示一个基于Spring MVC以及静态HTML页面通过JQuery ajax 实现登录的小Demo(保存Cookie、密码加盐加密)
代码很容易,逻辑也很简单,记录一下。

案例代码

html部分
<form class="login-form" onkeydown="if(event.keyCode==13){return false;}">
        <h3 class="form-title">登录</h3>
        <div class="alert alert-danger display-hide ">
            <button class="close" data-close="alert"></button>
            <span id="errormsg">没有输出任何账号密码 </span>
        </div>
        <div class="form-group">
            <!--ie8, ie9 does not support html5 placeholder, so we just show field title for that-->
            <label class="control-label visible-ie8 visible-ie9">账号</label>
            <div class="input-icon">
                <i class="fa fa-user"></i>
                <input class="form-control placeholder-no-fix" type="text"
                       autocomplete="off" placeholder="请输入账号" id="username" name="username"/></div>
        </div>
        <div class="form-group">
            <label class="control-label visible-ie8 visible-ie9">密码</label>
            <div class="input-icon">
                <i class="fa fa-lock"></i>
                <input class="form-control placeholder-no-fix" type="password"
                       autocomplete="off" placeholder="请输入密码" id="password" name="password"/></div>
        </div>
        <input type="hidden">
        <div class="form-actions">
            <label class="rememberme mt-checkbox mt-checkbox-outline">
                <input type="checkbox" id="remember"/> 记住我
                <span></span>
            </label>
            <button type="button" class="btn green pull-right" id="btn_submit"> 登录</button>
        </div>
JS部分
<script>

    $(document).ready(function () {
        //判断是否存在Cookie
        if ($.cookie("remember")) {
            $("#username").val($.cookie("username"));
            $("#password").val($.cookie("password"));
            $("#remember").prop("checked", true);
        }
    });

    $("#btn_submit").click(function () {
        var username = $("#username").val();
        var password = $("#password").val();
        //盐值
        var salt = "";

        if (username == "" || password == "") {
            $(".alert-danger").show();
            $("#errormsg").text("没有输出任何账号密码 ");
            return;
        }

        if (password != $.cookie("password")) {
            //修改为 同步
            $.ajaxSettings.async = false;
            $.get("/salt?username=" + username, function (data, status) {
                if (status == "success") {
                    salt = data;
                }
            });
            $.ajaxSettings.async = true;
            //MD5 加密
            password = $.md5(password);
            password = $.md5(password + salt);
        }
        //ajax 请求
        $.ajax({
            // 请求类型
            type: "post",
            // 请求URL
            url: "/login",
            // 请求参数
            data: {
                username: username,
                password: password
            },
            // 数据返回类型
            dataType: "json",
            // 默认为true 异步请求
            async: true,
            // 成功返回的结果(响应)
            success: function (data) {
                if (data == "1") {
                    // 判断 记住密码框是否选中
                    if ($("#remember").prop("checked")) {
                        $.cookie("username", username, {expired: 7});
                        $.cookie("password", password, {expired: 7});
                        $.cookie("remember", true, {expired: 7});
                    } else {
                        $.removeCookie("username");
                        $.removeCookie("password");
                        $.removeCookie("remember");
                    }
                    window.location.href = "index";
                }
                if (data == "0") {
                    $(".alert-danger").show();
                    $("#errormsg").text("账号或密码错误 ");
                }
            }
        });
    });
</script>
后端部分代码
/**登录控制器
 * @author ACI
 * @Title: LoginController
 * @ProjectName TestShop
 * @Description: TODO
 * @date 2019/1/11 21:54
 */
@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @GetMapping(value = "login")
    public String login() {

        return "login";
    }

    @ResponseBody
    @PostMapping(value = "login")
    public String login(User user, HttpServletRequest request) {

        User login = loginService.login(user);

        // 登陆失败
        if (login == null) {
            return "0";
        }
        //成功
        else {
            //保存Session
            request.getSession().setAttribute("login", login);
            return "1";
        }
    }
}
/**
 * 盐值管理
 * @author ACI
 * @Title: SaltManagerController
 * @ProjectName TestShop
 * @Description: TODO
 * @date 2019/1/15 16:35
 */
@Controller
public class SaltManagerController {

    @Autowired
    private LoginService loginService;

    @ResponseBody
    @GetMapping(value = "salt")
    public String getSaltByName(String username) {

        //获取盐值
        String saltByName = loginService.getSaltByName(username);

        System.out.println(saltByName);

        return saltByName;
    }
}

附:

JQuery.Cookie.js
/*!
 * jQuery Cookie Plugin v1.3.1
 */
(function ($, document, undefined) {

    var pluses = /\+/g;

    function raw(s) {
        return s;
    }

    function decoded(s) {
        return unRfc2068(decodeURIComponent(s.replace(pluses, ' ')));
    }

    function unRfc2068(value) {
        if (value.indexOf('"') === 0) {
            // This is a quoted cookie as according to RFC2068, unescape
            value = value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
        }
        return value;
    }

    function fromJSON(value) {
        return config.json ? JSON.parse(value) : value;
    }

    var config = $.cookie = function (key, value, options) {

        // write
        if (value !== undefined) {
            options = $.extend({}, config.defaults, options);

            if (value === null) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = config.json ? JSON.stringify(value) : String(value);

            return (document.cookie = [
                encodeURIComponent(key), '=', config.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path ? '; path=' + options.path : '',
                options.domain ? '; domain=' + options.domain : '',
                options.secure ? '; secure' : ''
            ].join(''));
        }

        // read
        var decode = config.raw ? raw : decoded;
        var cookies = document.cookie.split('; ');
        var result = key ? null : {};
        for (var i = 0, l = cookies.length; i < l; i++) {
            var parts = cookies[i].split('=');
            var name = decode(parts.shift());
            var cookie = decode(parts.join('='));

            if (key && key === name) {
                result = fromJSON(cookie);
                break;
            }

            if (!key) {
                result[name] = fromJSON(cookie);
            }
        }

        return result;
    };

    config.defaults = {};

    $.removeCookie = function (key, options) {
        if ($.cookie(key) !== null) {
            $.cookie(key, null, options);
            return true;
        }
        return false;
    };

})(jQuery, document);

JQuery.md5.js
/*!
 * jQuery Cookie Plugin v1.3.1
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
(function ($, document, undefined) {

    var pluses = /\+/g;

    function raw(s) {
        return s;
    }

    function decoded(s) {
        return unRfc2068(decodeURIComponent(s.replace(pluses, ' ')));
    }

    function unRfc2068(value) {
        if (value.indexOf('"') === 0) {
            // This is a quoted cookie as according to RFC2068, unescape
            value = value.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
        }
        return value;
    }

    function fromJSON(value) {
        return config.json ? JSON.parse(value) : value;
    }

    var config = $.cookie = function (key, value, options) {

        // write
        if (value !== undefined) {
            options = $.extend({}, config.defaults, options);

            if (value === null) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = config.json ? JSON.stringify(value) : String(value);

            return (document.cookie = [
                encodeURIComponent(key), '=', config.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path ? '; path=' + options.path : '',
                options.domain ? '; domain=' + options.domain : '',
                options.secure ? '; secure' : ''
            ].join(''));
        }

        // read
        var decode = config.raw ? raw : decoded;
        var cookies = document.cookie.split('; ');
        var result = key ? null : {};
        for (var i = 0, l = cookies.length; i < l; i++) {
            var parts = cookies[i].split('=');
            var name = decode(parts.shift());
            var cookie = decode(parts.join('='));

            if (key && key === name) {
                result = fromJSON(cookie);
                break;
            }

            if (!key) {
                result[name] = fromJSON(cookie);
            }
        }

        return result;
    };

    config.defaults = {};

    $.removeCookie = function (key, options) {
        if ($.cookie(key) !== null) {
            $.cookie(key, null, options);
            return true;
        }
        return false;
    };

})(jQuery, document);

02-01 13:28