登录注册常用JQuery逻辑

2017-11-03 19:52:43来源:CSDN作者:weixin_39641494人点击

分享

描述:
- jQuery:用于前段的js和Ajax处理
- SpringMVC:用于接收请求分发处理,返回JSON响应
SpringIOC:用于管理Controller,Service,Dao组件,注入关系.
降低组件之间的关联
- 所有请求采用Ajax方式与服务器端交互
所有请求响应的JSON统一格式为

{ "status":请求处理状态, "msg":消息, "data":数据}
  • ##登录功能

发送Ajax请求

-发送时机:登录按钮onclick
-请求参数:用户名和密码
-请求地址:/user/login.action

准备的类
- Result.class      用于对返回json数据的封装
- NoteUtil.class      用于MD5加密,利用UUID生成User的ID


UserMapper.xml
和以前一样没有什么改变.
UserServiceImpl

package com.qiushiju.service.impl;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.qiushiju.mapper.UserMapper;import com.qiushiju.model.User;import com.qiushiju.service.UserService;import com.qiushiju.util.NoteUtil;import com.qiushiju.util.Result;@Servicepublic class UserServiceImpl implements UserService {    @Autowired    private UserMapper userMapper;    @Override    public Result<User> checkLogin(String userName, String password) {        Result<User> result = new Result<User>();        User user = userMapper.getUserByName(userName);        if (user == null) {            result.setStatus(1);            result.setMsg("用户名错误");            return result;        }        String md5_pwd;        try {            md5_pwd = NoteUtil.md5(password);            if (!user.getCnUserPassword().equals(md5_pwd)) {                result.setStatus(2);                result.setMsg("密码错误");                return result;            }        } catch (Exception e) {            e.printStackTrace();        }        // 登录成功        result.setStatus(0);        result.setMsg("登录成功");        //密码可以屏蔽返回        //user.setCnUserPassword("");        result.setData(user);        return result;    }    @Override    public Result<Object> addUser(String userName, String userNick, String password) {        Result<Object> result = new Result<Object>();        User hasUser = userMapper.getUserByName(userName);        if (hasUser != null) {            result.setStatus(1);            result.setMsg("用户名已占用");            return result;        }        User user = new User();        user.setCnUserId(NoteUtil.createId());        user.setCnUserName(userName);        user.setCnUserNick(userNick);        try {            user.setCnUserPassword(NoteUtil.md5(password));        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        userMapper.addUser(user);        result.setStatus(0);        result.setMsg("注册成功");        return result;    }}

UserController.java

package com.qiushiju.controller;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.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import com.qiushiju.model.User;import com.qiushiju.service.UserService;import com.qiushiju.util.Result;@Controller@RequestMapping("/user")public class UserController {    @Autowired    private UserService userService;    @RequestMapping(value = "/login.action")    @ResponseBody    public Result<User> login(String userName, String password) {        Result<User> result = userService.checkLogin(userName, password);        return result;    }    @RequestMapping("/add.action") // 不写的method = RequestMethod.的话,就是默认两种都可以    @ResponseBody    public Result<Object> regis(String userName, String password, String userNick) {        Result<Object> result = userService.addUser(userName, userNick, password);        return result;    }}

Result.java

package com.qiushiju.util;public class Result<T> {    private Integer status; // 状态位,0表示成功,1表示用户名错误,2表示棉密码错误    private String msg;  // 各种信息,如登录成功,用户名错误,密码错误    private T data;   // 返回的数据.    public Integer getStatus() {        return status;    }    public void setStatus(Integer status) {        this.status = status;    }    public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }    public T getData() {        return data;    }    public void setData(T data) {        this.data = data;    }}

NoteUtil.java

package com.qiushiju.util;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.util.UUID;import com.alibaba.druid.util.Base64;public class NoteUtil {    public static String createId(){        UUID uuid = UUID.randomUUID();        return uuid.toString().replace("-","");    }    public static String md5(String c) throws Exception{        //将字符串信息采用MD5处理        MessageDigest md = MessageDigest.getInstance("MD5");        // 将MD5处理结果利用base64转成字符串        byte[] output = md.digest(c.getBytes());        String s = org.apache.tomcat.util.codec.binary.Base64.encodeBase64String(output);        return s;    }    public static void main(String[] args) throws Exception {        System.out.println(createId());        System.out.println(md5("123456"));    }}

log_in.html

<!DOCTYPE html><html><head><meta charset="UTF-8"><link rel="stylesheet" href="styles/login.css"/><script type="text/javascript"     src="scripts/jquery.min.js"></script><script type="text/javascript"    src="scripts/basevalue.js"></script><script type="text/javascript"     src="scripts/cookie_util.js"></script><script type="text/javascript"    src="scripts/login.js"></script></head>    <body>        <div class="global">            <div class="log log_in" tabindex='-1' id='dl'>                <dl>                    <dt>                        <div class='header'>                            <h3>登&nbsp;录</h3>                        </div>                    </dt>                    <dt></dt>                    <dt>                        <div class='letter'>                            用户名:&nbsp;<input type="text" name="" id="count" tabindex='1'/>                            <span id="count_span"></span>                        </div>                    </dt>                    <dt>                        <div class='letter'>                            密&nbsp;&nbsp;&nbsp;码:&nbsp;<input                            type="password" name="" id="password" tabindex='2' /> <span id="password_span"></span>                        </div>                    </dt>                    <dt>                        <div>                            <input type="button" name="" id="login" value='&nbsp登&nbsp录&nbsp' tabindex='3'/>                            <input type="button" name="" id="sig_in" value='&nbsp注&nbsp册&nbsp' tabindex='4'/>                        </div>                    </dt>                </dl>            </div>            <div class="sig sig_out" tabindex='-1' id='zc' style='visibility:hidden;'>                <dl>                    <dt>                        <div class='header'>                            <h3>注&nbsp;册</h3>                        </div>                    </dt>                    <dt></dt>                    <dt>                        <div class='letter'>                            用户名:&nbsp;<input type="text" name="" id="regist_username" tabindex='5'/>                            <div class='warning' id='warning_1'><span id="warning_1 span">该用户名不可用</span></div>                        </div>                    </dt>                    <dt>                        <div class='letter'>                            昵&nbsp;&nbsp;&nbsp;称:&nbsp;<input type="text" name="" id="nickname" tabindex='6'/>                        </div>                    </dt>                    <dt>                        <div class='letter'>                            密&nbsp;&nbsp;&nbsp;码:&nbsp;<input type="password" name="" id="regist_password" tabindex='7'/>                            <div class='warning' id='warning_2'><span id="warning_2 span">密码长度过短</span></div>                        </div>                    </dt>                    <dt>                        <div class='password'>                            &nbsp;&nbsp;&nbsp;确认密码:&nbsp;<input type="password" name="" id="final_password" tabindex='8'/>                            <div class='warning' id='warning_3'><span id="warning_3 span">密码输入不一致</span></div>                        </div>                    </dt>                    <dt>                        <div>                            <input type="button" name="" id="regist_button" value='&nbsp注&nbsp册&nbsp' tabindex='9'/>                            <input type="button" name="" id="back" value='&nbsp返&nbsp回&nbsp' tabindex='10'/>                            <script type="text/javascript">                            function get(e){                                return document.getElementById(e);                            }                            get('sig_in').onclick=function(){                                get('dl').className='log log_out';                                get('zc').className='sig sig_in';                            }                            get('back').onclick=function(){                                get('zc').className='sig sig_out';                                get('dl').className='log log_in';                            }                            window.onload=function(){                                var t =setTimeout("get('zc').style.visibility='visible'",800);                                get('final_password').onblur=function(){                                    var npassword=get('regist_password').value;                                    var fpassword=get('final_password').value;                                    if(npassword!=fpassword){                                        get('warning_3').style.display='block';                                    }                                }                                get('regist_password').onblur=function(){                                    var npassword=get('regist_password').value.length;                                    if(npassword<6&&npassword>0){                                        get('warning_2').style.display='block';                                    }                                }                                get('regist_password').onfocus=function(){                                    get('warning_2').style.display='none';                                }                                get('final_password').onfocus=function(){                                    get('warning_3').style.display='none';                                }                            }                            </script>                        </div>                    </dt>                </dl>            </div>        </div>    </body></html>

login.js类

/** * 主处理 */$(function() {    // 登录按钮处理    $("#login").click(login);    // 注册按钮处理    $("#regist_button").click(regist);});/** * 登录处理 */function login() {    // 清除提示信息    $("#count_span").html("");    $("#password_span").html("");    // 1.获取请求参数    // var 属性名,要与controlller层一致    var userName = $("#count").val().trim(); // .trim()去空    var password = $("#password").val().trim();    // 2.检查参数格式    // true通过检测;false未通过检测    var check = true;    if (userName == "") {        $("#count_span").html("用户名为空");        check = false;    }    if (password == "") {        $("#password_span").html("密码为空");        check = false;    }    // 3.发送Ajax请求    if (check) {        $.ajax({            url : base_path + "/user/login.action",            type : "post",            data : {                // ""引号内要与controller参数保持一致                // : 后的要与上面的var 属性名 保持一致                "userName" : userName,                "password" : password            },            dataType : "json",            // ajax的回调函数:发送请求经过后台处理将结果返回到此函数中,并利用js将页面更新            // result 是后台controller返回的一个json格式的数据result            success : function(result) {                if (result.status == 0) { // 0 表示登录成功                    var user = result.data;                    // 获取返回的用户ID,存入Cookie                    // var userId = result.data.cnUserId; // 对应实体类的属性                    // 获取返回的令牌号,存入Cookie                    // var token = result.data.cnUserToken;                    // 调用cookie_util.js函数写入cookie                    // addCookie("userId", userId, 2);                    // addCookie("token", token, 2);                    addCookie("uid", user.cnUserId, 2);                    addCookie("uname", user.cnUserName, 2);                    // 跳转到指定页面                    window.location.href = "edit.html";                } else if (result.status == 1) { // 1 表示用户名错误                    $("#count_span").html(result.msg);                } else if (result.status == 2) { // 2表示密码错误                    $("#password_span").html(result.msg);                }            },            error : function() {                alert("登录异常");            }        });    }};/** * 注册处理 */function regist() {    // 清空提示信息    $("#warning_1 span").html("");    $("#warning_2 span").html("");    $("#warning_3 span").html("");    $("#warning_1").hide();    $("#warning_2").hide();    $("#warning_3").hide();    // 获取请求参数    var name = $("#regist_username").val().trim();    var nick = $("#nickname").val().trim();    var password = $("#regist_password").val().trim();    var final_password = $("#final_password").val().trim();    // 检查格式    var check = true;    if (name == "") {        $("#warning_1 span").html("用户名为空");        $("#warning_1").show();        check = false;    }    if (password == "") {        $("#warning_2 span").html("密码为空");        $("#warning_2").show();        check = false;    } else if (password.length < 6) {        $("#warning_2 span").html("密码大于等于6位");        $("#warning_2").show();        check = false;    }    if (final_password == "") {        $("#warning_3 span").html("确认密码为空");        $("#warning_3").show();        check = false;    } else if (final_password != password) {        $("#warning_3 span").html("与密码不一致");        $("#warning_3").show();        check = false;    }    // 发送Ajax请求    if (check) {        $.ajax({            url : base_path + "/user/add.action",            type : "post",            data : {                "userName" : name,                "userNick" : nick,                "password" : password            },            dataType : "json",            success : function(result) {                if (result.status == 0) { // 成功                    // 提示成功                    alert(result.msg);                    // 切换到登录页面                    $("#back").click(); // 出发点击事件                } else if (result.status == 1) {                    // 提示用户名已经占用                    $("#warning_1 span").html(result.msg);                    $("#warning_1").show();                }            },            error : function() {                alert("注册发生异常");            }        });    }};

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台