Spring MVC uses Ajax to submit requests asynchronously to complete login

Submit the form asynchronously with Ajax, log in and return the JSON data.

1、 Effect

2、 Configuration

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.it.springmvc" />

    <mvc:annotation-driven></mvc:annotation-driven>
    <bean id="jspViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <mvc:default-servlet-handler/>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
xmlns="http://java.sun.com/xml/ns/javaee" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" 
version="3.0">
  <display-name>springMVC</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
      <servlet-name>example</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>WEB-INF/springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


</web-app>

Controller

PersonController.java

package com.it.springmvc.controller;

import java.util.ArrayList;
import java.util.List;

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 org.springframework.web.servlet.ModelAndView;

import com.it.springmvc.entity.Person;

@Controller
public class PersonController {
    @RequestMapping(value="/toLogin",method=RequestMethod.GET)
    public String toLogin(){
        return "login";
    }

    @RequestMapping(value="/login",method=RequestMethod.POST)
    public String login(Person person){
        if(10025==person.getPid()&&"123".equals(person.getPwd())){
            return "redirect:queryAll";
        }else{
            return "login";
        }
    }
    @RequestMapping(value="/queryAll",method=RequestMethod.GET)
    public ModelAndView queryAll(){
        ModelAndView mav=new ModelAndView("show");
        List<Person> list=new ArrayList<Person>();
        list.add(new Person(10025, "tom", "123"));
        list.add(new Person(10026, "jakson", "123"));
        list.add(new Person(10027, "nikly", "123"));
        mav.addObject("list", list);
        return mav;
    }
    @RequestMapping("/ajax")
    @ResponseBody
    public Object ajax(Person person){
        System.out.println(person.getPid()+person.getPwd());
        if(10025==person.getPid()&&"123".equals(person.getPwd())){
            return "{\"flag\":true}";
        }else{
            return "{\"flag\":false}";

        }

    }

}

1.2.2.

Index.jsp

<body>
<%
response.sendRedirect("toLogin");
%>
</body>

login.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
    $("#sub").click(function(){
        $.post("ajax",$("form").serialize(),function(data){
            //alert(data.flag);
              if(data.flag){
                alert("Login success");
                location.href="queryAll";
            }else{
                alert("please recheck your usename and password");
            } 
        },'json');
    })
})
</script>
<body>
<form  method="post">
    <table border="1" width="300px">
        <tr>
            <td>usename</td>
            <td><input type="text" name="pid"/></td>
        </tr>
        <tr>
            <td>password</td>
            <td><input type="password" name="pwd"/></td>
        </tr>
        <tr>            
            <!-- <td colspan="2"><input type="submit" value="submit"/></td> -->
            <td colspan="2"><input type="button" value="submit" id="sub"/></td>
        </tr>
    </table>
</form>

</body>
</html>

show.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<a href="toAdd">Add</a>
<table border="1" width="400px">
    <tr>
        <th>NUM</th>
        <th>name</th>
        <th>password</th>
        <th>Act</th>
    </tr>
    <c:forEach var="person" items="${list}">
        <tr>
            <td>${person.pid }</td>
            <td>${person.pname }</td>
            <td>${person.pwd }</td>
            <td><a href="">Update</a></td>
            <td><a href="">DEL</a></td>

        </tr>
    </c:forEach>
</table>
</body>
</html>

Read More: