前端JQuery ajax实现Cookie以及MD5加盐加密

前言

本文展示一个基于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);

  • 6
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值