Ajax实现登录异步检测用户名或者密码是否正确

一、SpringMVC版

Controller

@RestController//加上这个不会返回到视图解析器
public class AjaxController { 

@RequestMapping("/a3")
    public String a3(String name,String pwd){
        String msg="";
         if(name!=null)
        {
            if("rk".equals(name)) {
                msg = "ok";
            }
            else{
                msg="用户名有误";
            }
        }
        if(pwd!=null)
        {
            if("123456".equals(pwd)){
                msg="ok";
            }
            else {
                msg = "密码有误";
            }
        }
        return msg; //由于@RestController注解,将msg转成json格式返回
    }
}

前端页面 login.jsp

<%--
  Created by IntelliJ IDEA.
  User: 16246
  Date: 2021/10/5
  Time: 12:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录页面</title>
    <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
    <script>

            function test1() {
                $.post({
                    url:"${pageContext.request.contextPath}/a3",
                    data:{"name":$("#username").val()},
                    success:function (data) {
                       console.log(data);//控制台打印信息
                       if(data.toString()==='ok')
                             $("#userinfo").css("color","green");
                       else
                             $("#userinfo").css("color","red");
                       $("#userinfo").html(data);
                    }
                })
            }

            function test2() {
                $.post({
                    url:"${pageContext.request.contextPath}/a3",
                    data:{"pwd":$("#password").val()},
                    success:function (data) {
                        console.log(data);
                        if(data.toString()==='ok')
                            $("#pwdinfo").css("color","green");
                        else
                            $("#pwdinfo").css("color","red");
                        $("#pwdinfo").html(data);
                    }
                })
            }
    </script>
</head>
<body>

<p>
    用户名:<input type="text" id="username" onblur="test1()">
    <span id="userinfo"></span>
</p>
<p>
    密码:<input type="text" id="password" onblur="test2()">
    <span id="pwdinfo"></span>
</p>

</body>
</html>

        流程:onblur:移出焦点事件 ----->test1()异步提交信息,请求访问/a3----->/a判断该用户是否存在,返回msg的json格式数据---->回调函数(success)解析后端返回的data,判断data设置css样式,然后在span标签中添加data

二、servlet版

        1、在lib中导入jar包

        2、前端页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<script src="${pageContext.request.contextPath}/js/jquery-3.6.0.js"></script>

<script>
    function test1() {
        $.post(
            {
                url:"${pageContext.request.contextPath}/rkServlet",
                data:{"namerk":$("#username").val()},
                success:function (data) {
                    if(data.msg==='ok')
                    {
                        $("#userinfo").css("color","green");
                    }else {
                        $("#userinfo").css("color","red");
                    }
                    $('#userinfo').html(data.msg);
                }
            }
        )

    }
</script>
<body>

<form>
    <p>
     用户名:<input type="text" id="username" onblur="test1()">
     <span id="userinfo"></span>
    </p>
</form>

</body>

</html>

        3、后端rkServlet

package cn.rk.web.servlet;
import cn.rk.domain.info;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/rkServlet")
public class rkServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("namerk");
        System.out.println("name:"+name);
        String msg="agfadf";
            if("rk".equals(name))
            {
                msg="ok";
            }else {
                msg="用户名错误";
            }
        System.out.println(msg);
        //将info对象序列化为json
         ObjectMapper mapper=new ObjectMapper();
        info in=new info(msg,true);
        String json = mapper.writeValueAsString(in);
        //将json数据写回客户端
        //设置content-type
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
 }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

        要将需要传给前端页面的数据用对象封装起来,然后通过mapper的writeValueAsString转化为json对象

info类

public class info {
    private String msg;
    private Boolean flag;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Boolean getFlag() {
        return flag;
    }

    public void setFlag(Boolean flag) {
        this.flag = flag;
    }

    public info(String msg, Boolean flag) {
        this.msg = msg;
        this.flag = flag;
    }

    public info() {
    }

}

结果:

 

猜你喜欢

转载自blog.csdn.net/m0_46979453/article/details/120613488