登陆中的Ajax实现

$("#loginButton").click(function () {
    if($("#adminId").val()==''&&$("#passwd").val()==''){
        $("#info").text("提示:账号和密码不能为空");
    }
    else if ($("#adminId").val()==''){
        $("#info").text("提示:账号不能为空");
    }
    else if($("#passwd").val()==''){
        $("#info").text("提示:密码不能为空");
    }
    else if(isNaN($("#adminId").val())){
        $("#info").text("提示:账号必须为数字");
    }
    else {
        $.ajax({
            type: "POST",
            url: "/api/loginCheck",
            data: {
                id:$("#adminId").val() ,
                password: $("#passwd").val()
            },
            dataType: "json",
            success: function(data) {
                if(data.stateCode.trim() == "0") {
                    $("#info").text("提示:该用户不存在");
                } else if(data.stateCode.trim() == "1") {
                    $("#info").text("提示:密码错误");
                } else if(data.stateCode.trim() == "2"){
                    $("#info").text("提示:登陆成功,跳转中...");
                    window.location.href="/admin/main";
                }
            }
        });
    }
})




<div class="form-inline"  >
    <h2 style="text-align: center;font-family: 'Adobe 楷体 Std R';color: black">Graduation Design</h2>
    <div class="input-group">
        <span class="input-group-addon">账号</span>
        <input type="text" class="form-control" name="id" id="adminId">
    </div><br/><br/>
    <div class="input-group">
        <span class="input-group-addon">密码</span>
        <input type="password" class="form-control" name="passwd" id="passwd">
    </div>
    <br/>
    <p style="text-align: right;color: red;position: absolute" id="info"></p>

    <br/>
    <button id="loginButton"  class="btn btn-primary">登陆
    </button>

</div>



// 0:用户不存在  1:密码错误 2:登陆成功
@RequestMapping(value = "/api/loginCheck", method = RequestMethod.POST)
public @ResponseBody Object loginCheck(HttpServletRequest request,HttpServletResponse httpServletResponse) {
    int id=Integer.parseInt(request.getParameter("id"));
    String passwd = request.getParameter("password");
    HashMap<String, String> res = new HashMap<String, String>();
    if(adminService.getById(id)==null){
        res.put("stateCode", "0");
    }
    else if(!adminService.getById(id).getPassword().equals(passwd)){
        res.put("stateCode", "1");
    }else {
        String ip=request.getRemoteAddr();
        AdminLoginLog adminLoginLog=new AdminLoginLog();
        adminLoginLog.setAdminId(id);
        adminLoginLog.setDate(new Date());
        adminLoginLog.setIp(ip);
        int log=adminLoginLogService.insert(adminLoginLog);
        Cookie cookie = new Cookie("userId",""+id);
        cookie.setMaxAge(3600*24);
        httpServletResponse.addCookie(cookie);
        request.getSession().setAttribute("admin",adminService.getById(id));
        res.put("stateCode", "2");
    }


猜你喜欢

转载自blog.csdn.net/weixin_40797576/article/details/79986102