Recorded in detail in SpingBoot, using Ajax to determine whether the username and password exists, and the process of setting the cookie value

I have been wanting to understand Ajax and Cookie related technologies since I was a professional, until I completed the development project, and I finally understood it. I wrote this article as a record, and it can also be used as a simple understanding for beginners.
First, let's take a look at the form form of the front-end page:

<div class="form-signin text-center">
	        <h2 class="form-signin-heading">请登录</h2>
	        <label for="inputUserName" class="sr-only">用户名</label>
	            <input type="email" id="inputUserName" class="form-control s-margin-2" placeholder="用户名" required autofocus>
	        <label for="inputPassword" class="sr-only">密码</label>
	            <input type="password" id="inputPassword" class="form-control s-margin-1" placeholder="密码" required>
	        <button class="btn btn-lg btn-primary btn-block s-margin-2" onclick="userLogin()">登录</button>
			<button class="btn btn-lg btn-default btn-block s-margin-2" onclick="toRegister()">注册</button>
 </div >

Below is the JS code:

function userLogin() {
    
    
		    var user = {
    
    };
		    user.userName = document.getElementById("inputUserName").value;
		    user.userPassword = document.getElementById("inputPassword").value;
		    var response;
            $.ajax({
    
    
                async : false,//发送同步请求
                type : 'POST',  //请求方式为post
                url : address+"userLogin",  //发送请求的地址。
                data : user,  //发送到服务器的数据
                dataType : 'json',//预期服务器返回的数据类型
                success : function(result) {
    
    
                    response = result;
                },
                error : function(result) {
    
    
                    alert('服务器异常');
                }
            });

			if(response.status == "0"){
    
    
			    setCookie("user",response.content,1);
			    window.location.href=address+"words.html";
			}
			else{
    
    
			    alert(response.content);
			}
        }

The function we want to complete is to verify the login form through Ajax and set the cookie.
Below, we use blue text to record the entire code execution process 1. By clicking the login button, trigger the function 2. Execute the function in JS 3. Get the user name , The data entered in the password is stored in the user variable 4. Ajax is performed for front-end interaction

"userLogin()"
"userLogin()"



The following introduces the common parameters of ajax

1. url : String type parameter, (default is the current page address) the address where the request is sent.

2.type : String type parameter, the request method (post or get) defaults to get. : You can use other http request methods, such as put and delete, but only some browsers support it.

3.timeout : : Number type parameter, set the request timeout time (milliseconds)

4. async : Boolean type parameter, the default setting is true: all requests are asynchronous requests, that is, at the same time as data requests, other code statements can also be executed synchronously. false: To send synchronous requests, they must be executed one by one. The previous code is not over, the code behind is in a blocking state

5.cache : Boolean type parameter, the default is true (when the dataType is script, the default is false): If set to false, the request information will not be loaded from the browser cache.

6.data : Object or String type parameter, the data sent to the server: If it is not a string, it will be automatically converted to a string format. The get request will be appended to the url: the
object must be in key/value format, for example {k1:"v1",k2:"v2"} is converted to &k1=v1&k2=v2. If it is an array, JQuery will automatically assign different values ​​to the same name. For example {v:["k1","k2"]} translates to &k=v1&k=v2.

7. dataType : String type parameter, expected data type returned by the server.
1) xml: Returns an XML document, which can be processed by JQuery.
2) script: returns plain text JavaScript code. Results are not automatically cached. Unless the cache parameter is set. Note that when making remote requests (not under the same domain), all post requests will be converted to get requests.
3) json: returns JSON data. : ·
4) jsonp: JSONP format. When calling a function in SONP form, such as myurl?callback=?, JQuery will automatically replace the last "?" with the correct function name to execute the callback function.
5) text: returns a plain text string.
6) html: returns plain text HTML information; the included script tag will be executed when inserted into the DOM. : :
If not specified, JQuery will automatically return responseXML or responseText according to the http package mime information, and pass it as a callback function parameter.

8.beforeSend : Requires a parameter of type Function, which can modify the function of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. If you return false in beforeSend, you can cancel this ajax request. The XMLHttpRequest object is the only parameter.
function(XMLHttpRequest){ this; //The options parameter passed when calling this ajax request
}

9.complete : The parameter is required to be a Function type, and the callback function to be called after the request is completed (called when the request succeeds or fails). Parameters: XMLHttpRequest object and a string describing the type of successful request.
function(XMLHttpRequest, textStatus){ this; //The options parameter passed when calling this ajax request }

10.success : The parameter is required to be a Function type, and the callback function called after the request is successful. There are two parameters.
(1) The data returned by the server and processed according to the dataType parameter.
(2) A string describing the state.
function(data, textStatus){ //data may be xmlDoc, jsonObj, html, text, etc. this; //the options parameter passed when calling this ajax request }


11.error : Requires a parameter of type Function, the function to be called when the request fails. This function has 3 parameters, namely XMLHttpRequest object, error message, captured error object (optional). The ajax event function is as follows:
function(XMLHttpRequest, textStatus, errorThrown){ //Usually only one of textStatus and errorThrown contains information this; //The options parameter passed when calling this ajax request }


12.contentType: The parameter is required to be String type. When sending information to the server, the content encoding type defaults to "application/x-www-form-urlencoded". This default value is suitable for most applications.

Let's look down, let's look at the code first, and then look at the steps to analyze
UserController.java

    /**
     * 用户登录
     * @param userName
     * @param userPassword
     * @return
     */
    @PostMapping(value = "/userLogin")
    public Response userLogin(@RequestParam("userName")String userName,
                              @RequestParam("userPassword")String userPassword){
    
    
        return userService.userLogin(userName,userPassword);
    }


}

6. The backend urmatches the corresponding path according to the l path. Controller
7. Enter the method , and the parameter userLoginreceives the value passed in by ajax .
UserService中userLoginUserServiceImpl

UserService:

import com.leaveword.utils.Response;

    public interface UserService {
    
    
        Response getUser(Integer userId);
        Response userRegister(String userName,String userPassword);
        Response userLogin(String userName,String userPassword);
}

Show UserServiceImpl code:

    @Override
    public Response userLogin(String userName, String userPassword) {
    
    
        //判断是否输入
        if(CommonTools.isEmpty(userName))
            return new Response("-1","用户名不能为空");
        if(CommonTools.isEmpty(userPassword))
            return new Response("-1","用户密码不能为空");
        //判断数据库是否存在
        User user = userRepository.findByUserName(userName);
        if(user != null){
    
    
            if(user.getUserPassword().equals(userPassword)) {
    
    
                user.setUserPassword("");
                return new Response("0", JSON.toJSONString(user));
            }
            else
                return new Response("-1","密码错误");
        }
        else
            return new Response("-1","用户不存在");
    }

9. Through CommonToolsthe method in the class isEmpty, determine whether the input box is input
remember here, if the query is successful, there are two parameters in the Response, the first is assigned 0, and the second is assigned the JSON data converted by user

Show CommonTools code:


import java.sql.Timestamp;

public class CommonTools {
    
    
    public static boolean isEmpty(String str){
    
    
        if(str == null)
            return true;
        if(str.isEmpty())
            return true;
        if(str == "" || str.equals(""))
            return true;
        return false;
    }

    public static Timestamp getCurrentTime(){
    
    
        return new Timestamp(System.currentTimeMillis());
    }
}

10. Then userRepositoryquery the database whether there is the username and password
UserRepository passed from the page:

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User,Integer> {
    
    
    User findByUserName(String userName);
}


11. Return the result to a variable Responseof typeresponse
Response:

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Response {
    
    
    private String status;
    private Object content;
}

Notice: The response variable has now obtained two values, 标识符:statusand 内容:content, return the variable from Service and Controller in turn, and finally respond to the front-end Ajax.

12. The front-end page Ajax obtains the result through Ajax.
If the request is successful, assign it to success : function(result)in result, and then assign it to the front end responseVariables
If the request fails, a prompt box will pop up alert('服务器异常'), indicating that the server is abnormal

Let's explain how to set cookies
. Let's put the code for setting cookies in the front-end js code.

if(response.status == "0"){
    
    
			    setCookie("user",response.content,1);
			    window.location.href=address+"words.html";
			}
else{
    
    
			    alert(response.content);
			}

We know that if the post request in ajax is successful, two variables will be brought into the response, and the success will be
13. To determine response.statuswhether it is 0
, if not 0, then put contentit in the prompt box and display it.
If it is 0, it represents the request It did succeed. Then, call the setCookie()method

setCookie() in util.js and define the specific method in util.js. The code of util.js is shown below.

function setCookie(name, value, days) {
    
    
    var d = new Date;
    d.setTime(d.getTime() + 24*60*60*1000*days);//设置Cookie保存的时间
    window.document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
   
    var strCookie=window.document.cookie;
     alert("function setCookie里"+strCookie);//弹窗提示
}

14. Call setCookie() to assign
the following parameters of common cookies

1.name : required parameter, this is the variable name of the cookie
2.value : optional parameter, the value of this cookie variable
3.expire : optional parameter, this is used to set the time when the cookie variable is saved. 1). The time saved by the cookie variable is the UNIX timestamp minus the current UNIX timestamp. (UNIX timestamp: is the number of seconds elapsed since January 1, 1970 (midnight in UTC/GMT).
2). Obtain the current UNIX timestamp through the time() function, plus the time we want to save (in seconds) Eg:setcookie("user", "Big Fish Sea", time()+3600), so We can save the user cookie variable for 3600 seconds
3). Delete the cookie variable by setting the timestamp less than the current timestamp, Eg:setcookie("user","big fish sea",time()-1 ) so that we delete the user cookie variable.
4.path : The valid range of the cookie.
1) This parameter is the valid range based on the next parameter domain. If the path is set to "/", it is valid in the entire domain, Eg:setcookie("user","big fish sea",time()+3600 ,"/"), so that any directory and any file under our domain can call the value of this cookie variable.
2) If the path is set to "/test", then only the /test directory and subdirectories under the domain are valid. For example, there are two directories under the domain: test1, test2, we set it to setcookie("user", "big fish" Hai,time()+3600,"/test1"), then the value of the user cookie variable can only be called in the test1 directory, but not in the test2 directory.
5.domain : The domain name of the cookie is valid. If the domain is set to dayuhai.cn, then all subdomains under dayuhai.cn are valid. Eg:dayuhai.n has two subdomains, java.dayuhai.cn, css.dayuhai.cn, we set it as setcookie("user","big fish sea",time()+3600,"/","java. dayuhai.cn”), then the value of the user cookie variable can only be obtained under the subdomain of java.dayuhai.cn.
6.secure : Set whether the cookie only passes through secure https, the value is 0 or 1, if the value is 1 , the cookie is only valid on https connections, the default value is 0, which means that cookies are valid on both http and https connections.

Next, we explain in detail the meaning of the code in the setCookie() function.
d.setTime(d.getTime() + 24 60 60 1000 days):

  • d. getTime(): Get the time in milliseconds at the time point d (that is, the number of milliseconds elapsed from 0:0:00:00 on January 1, 1970 to the time point d, the computer generally sets 1970 January 1st, 0:00:00 is the initial time)
    24 60 60 1000 days : 24 (24 hours a day) * 60 (one hour 60 minutes) * 60 (one minute 60 seconds) * 1000 (one second 1000 milliseconds) *days gets the number of milliseconds corresponding to days.
  • d.setTime(d.getTime() + 24 60 60 1000 days) : Add the number of milliseconds corresponding to the expiration date, and then use the d.setTime() method to assign it to the d object.

Here we save the cookie for 1 day

window.document.cookie = name + “=” + value + “;path=/;expires=” + d.toGMTString()

  • d.toGMTString(): Indicates that the date will be converted from the local time zone to the GMT time zone before being converted to a string.

window.document.cookie = means assigning a value to a cookie. What kind of value is assigned? It is valid for all subdomains of the domain name, the storage time is 1 day, and the format is the value of "name=value".

Let's put the front-end JS code for a better explanation

	if(response.status == "0"){
    
    
			    setCookie("user",response.content,1);
			    window.location.href=address+"words.html";
			}
			else{
    
    
			    alert(response.content);
			}

15. After setting the cookie, the page will jump to complete the login function

Summary:
1. Ajax request: send data to the back-end through the parameters set by ajax, complete the verification in the corresponding function, and return the result to the front-end to achieve feedback
2. Set Cookie: When the login verification is completed, call setCookie() method, set according to the corresponding condition parameters of the cookie

insert image description here

Guess you like

Origin blog.csdn.net/qq_30336973/article/details/124424496