The method of spring MVC + Ajax for information verification


This article is an introduction to using Ajax with spring MVC. First, let’s learn what AJAX is

AJAX is not a new programming language, but a new way to use existing standards. The biggest advantage of AJAX is that it can exchange data with the server and update part of the web content without reloading the whole page. So AJAX is very important for improving the user experience

XMLHttpRequest is the foundation of Ajax.

There are two main methods:

var xmlhttp=new XMLHttpRequest();,url,async)

Among the parameters in the open method, method represents the type of request (get / post), URL represents the location of the resource to be requested, and async represents whether to start the asynchronous request. This value is generally filled with true, because it is faster, and the process will not be suspended due to the slow response of the server

The send method is, of course, the act of making a request

Note here: if you need post data like HTML forms, use setrequestheader () to add HTTP headers. Then specify the data you want to send in the send () method:"POST","url",true);
Xmlhttp. Setrequestheader ("content type", "application / x-www-form-urlencoded"); // this is very important and useful

The second line in the above code indicates the data type to be sent. In fact, we usually use it to specify that the common value of the sending type is JSON type, that is, “application / JSON”. Why is JSON type commonly used? Think about it. When we want to send multiple values, if one parameter is to be organized, how troublesome it will be. After the server gets the data, we need to take the data out of the request.parameter one by one, which is a waste of time. Therefore, with JSON, we can write the data into JSON format first, and then send it to the back end, which will automatically parse, It is very convenient to automatically fill the data into the corresponding POJO,

But to do this, we need the following configuration:

(1) Set the content type to “application / JSON” to tell the server that it is JSON

(2) Use json.stringify to convert data to JSON string and then transfer it

(3) The server controller needs to use @ requestbody before the parameters of the method, so the server will call the corresponding parser to parse the request

Here we have a complete request to complete! After reading the request, let’s look at the response again. The function of Ajax to accept the response is as follows:

Xmlhttp. Onreadystatechange = function() // Auto call
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
   Xmldoc = xmlhttp.responsexml; // get the value

When Ajax receives a response, it automatically callsonreadystatechangeMethod, and then get the return value through responsexml, then we will encounter a problem: in spring MVC, the return value will be written to modelandview, and then find the view, and render the data to the view, which cannot achieve the effect we want, that is, return the data without specifying the view, so we need to use @ ResponseBody

After declaring @ requestbody, if the return value is a string, the string will be written directly to the client. If it is an object, the object will be converted into a JSON string and then written to the client. Note here that if you return an object, press UTF-8 to encode it. If string is returned, the code is iso8859-1 by default, and the page may appear garbled. So in the annotation, we can modify the encoding format manually, such as @ requestmapping(value="/cat/query",produces="text/html;charset=utf-8"),The first is the path of the request, followed by the encoding format. On the client side, after getting the JSON string, you can use JSON. Parse() to convert the response to a JSON object, which is convenient to use

An instance Demo:

The form is as follows:

<form role="form" action="userController/">
    < label for = "exampleinputemail1" > user name < / label > < input name = "username" type = "text"
    <h5 style="color:red" id = "usernameInfo"></h4>

    < label for = "exampleinputpassword1" > password < / label > < input name = "password" type = "password"
    <h5 style="color:red"></h4>
    < label for = "exampleinputpassword1" > confirm password < / label > < input name = "repassword" type = "password"
    <h5 style="color:red"></label>
  < button type = "submit" > submit < / button >

The form triggers the JS code check() of the check by an onblur trigger that loses focus

var check = function(info){
  if ("username"){
    var username = document.getElementById("exampleInputEmail1").value.trim();
    if (username=="") {
      Document.getelementbyid ("usernameinfo"). InnerHTML = "user name cannot be empty";
      Loadxmldoc(); // perform Ajax check
/////Split line
  }else if ("password"){
      var pass=document.getElementById("exampleInputPassword1").value.trim();
      if (pass==""){
        Document. Getelementbyid ("passinfo"). InnerHTML = "password cannot be empty";
    var value1=document.getElementById("exampleInputPassword2").value;
    var value2=document.getElementById("exampleInputPassword1").value;
    if (value1!=value2){
      Document. Getelementbyid ("repassinfo"). InnerHTML = "passwords are inconsistent";

The above code is almost the same, so it’s almost the same only by looking at the partition line. On the partition line, first use the local JS to check whether the user input is empty, and then if not, execute the Ajax code to check whether the account has been occupied. The Ajax code is as follows:

var loadXMLDoc=function() {
  var xmlhttp=new XMLHttpRequest();
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
      var text=xmlhttp.responseText;
      Document. Getelementbyid ("usernameinfo"). InnerHTML = text; // set feedback
  Var name = document.getelementbyid ("exampleinputemail1"). Value; // get user input
  Xmlhttp. Open ("get", "usercontroller / checkinfo. Do? Username =" + name, true); // construct the request
  Xmlhttp. Send(); // send

Finally, look at the code of the controller:

@Requestmapping (value = "/ checkinfo", produces = {"text / HTML; charset = UTF-8;"}) // set the encoding
  @ResponseBody // set response to JSON
  public String check(HttpServletRequest requst) {
    String username = requst.getParameter("username");
    Integer id = userservice. Check (username); // check whether the account already exists
    If (ID! = null) {9 return "the account already exists";
    }else {
      return "";

Results show:

Use js to remind that the password cannot be empty


Using Ajax to check whether the account is repeated, and using JS to check whether the password is consistent before and after


The above is the spring MVC + Ajax information verification method introduced by Xiaobian to you. I hope it can help you. If you have any questions, please leave a message to me, and Xiaobian will reply to you in time. Thank you very much for your support of the developepaer website!
If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!