[back end integration] new program Day6

1. SpringMVC

1.1 restFul style

1.1.1 traditional get submission

url1: http://localhost:8080/findUser?name=tomcat&age=18
url2: http://localhost:8080/findUser?name=tomcat&age=18&sex= male

Requirements: the above parameter transfer can be simplified!
Simplified:
url3: http://localhost:8080/findUser/tomcat/18/ male  

1.1.2 restFul style description

Case: url3: http://localhost:8080/findUser/tomcat/18/ Male (send)
requirement:
1. Once the location of restful style data is determined, it cannot be modified
2. Parameters are separated by "/"
3. restFul style is applicable to get/post/put/delete request types
Type of request: get/post/put/delete

  1.1.3 editing backend Controller

  /**
     * URL Address:
     *  http://localhost:8080/findUser/tomcat/18/Male get type
     * Parameter: name/age/sex
     * Return value: the data obtained by the return value
     * restFul Syntax:
     *     1. Use / split between parameters
     *     2. Parameters to be received use {} packages
     *     3. The @ PathVariable value is used when receiving parameters
     */
    @RequestMapping("/findUser/{name}/{age}/{sex}")
    public String findUser(@PathVariable String name,
                           @PathVariable int age,
                           @PathVariable String sex){

        return name+":"+age+":"+sex;
    }

  1.1.4 test effect

 1.2 JSON

1.2.1 JSON introduction

JSON(JavaScript Object Notation) is a lightweight data exchange format. It makes it easy for people to read and write. At the same time, it is also convenient for the machine to analyze and generate. It is a subset of JavaScript programming language, standard ecma-262 3rd Edition - December 1999. JSON adopts a text format completely independent of the program language, but it also uses the habit of C-like language (including C, C++, C#, Java, JavaScript, Perl, Python, etc.). These features make JSON an ideal data exchange language.

  1.2.2 JSON format - object format

An object is an unordered collection of 'name / value' pairs. An object starts with "{" (left parenthesis) and ends with "}" (right parenthesis). Each "name" is followed by a ":" (colon); "," (comma) is used to separate the 'name / value' pairs`

  Example: the '' key can be written or not

	{"id": "100","name": "tomcat", "age": "18"}

  1.2.3 JSON format - array format

An array is an ordered collection of value s. An array starts with "[" (left bracket) and ends with "]" (right bracket). Values are separated by "," (comma).

	[100,"Zhang San",true]

1.2.4 JSON format - nested format  

The value can be a double quoted string, number, true, false, null, object, or array. These structures can be nested.

 [100,true,["a","b",{"name":"Zhang San","hobbys": ["having dinner","sleep"]}]]

1.3 spring MVC front and back end interaction - @ ResponseBody

1.3.1 business description

Problem description 1: when the front end accesses the back-end server, Ajax is generally used for data transmission. The back-end server usually returns data in JSON format to the front-end page
Problem description 2: how does the back-end server receive the parameters of the front-end. servlet mechanism

Question: how does the backend server return JSON strings

1.3.2 case test  

Requirement: query the User by name/age, and return the JSON string of the User object
URL: http://localhost:8080/findJSON?name=tomcat&age=18

/**
     * URL: http://localhost:8080/findJSON?name=tomcat&age=18  get
     * Parameter: name = Tomcat & age = 18
     * Return value: JSON of User object
     * Knowledge points:
     *      1.@ResponseBody //Convert the return value into JSON string, which is used most!!!
     *      2.If String type is returned, @ ResponseBody returns the String itself to the front end
     */
    @RequestMapping("/findJSON")
    @ResponseBody //Converts the return value to a JSON string
    public User findJSON(User user){
        //Extending data at the business tier
        user.setId(101);
        user.setSex("male");
        return user;
    }

1.3.3 test results

  1.4 @RestController annotation

1.4.1 editing RestUserController

package com.jt.controller;

import com.jt.pojo.User;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

//@Controller / / hand over the class to spring MVC for management
//@ResponseBody / / all methods in the current class return JSON strings
@RestController // = @Controller + @ResponseBody
@RequestMapping("/rest")
public class RestUserController {

    /**
     * matters needing attention:
     *      1.springMVC The request path in cannot be repeated!!!!
     *      2.You can customize the prefix @ RequestMapping("/ business name")
     * @return
     */
    @RequestMapping("/findJSON")
    public User findUser(User user){
        user.setId(105);
        user.setSex("male");
        return user;
    }
}

1.4.2 test effect

  Knowledge summary

restFul style
characteristic:
1. Write parameters to url and use / split
2. When receiving, use {xxxx} and @ PathVariable annotation to obtain
3. The request type post/put/get/delete is supported
JSON string
Format: 1. Object format 2. Array format
Nested format: value can be nested
Error prone item: json format must be added with "" sign
Notes:
1.@ResponseBody converts the return value to JSON
2.@RestController converts all return values of the current class into JSON

2. Front and back end business interaction  

2.1 project environment construction

  2.2 Axios explanation

2.2.1 introduction to Ajax

Ajax, namely Asynchronous Javascript And XML (Asynchronous Javascript And XML), was a new term proposed by Jesse James Garrett in 2005 to describe a 'new' method using a collection of existing technologies, including HTML or XHTML, CSS, JavaScript, DOM, XML, XSLT, and the most important XMLHttpRequest. [3] Using Ajax technology, web applications can quickly present incremental updates on the user interface without reloading (refreshing) the whole page, which makes the program respond to user operations faster.
Functions and functions:   Ajax mainly realizes front - end and back - end interaction and improves the interaction efficiency between user pages and servers
Features: local refresh, asynchronous access

2.2.2 Ajax asynchronous principle description

component:
1. Users
two   Ajax engine – proxy
3. Server

Asynchronous features:
1. The Ajax engine directly accesses the back-end server.
2. Before the callback function is executed, users can execute their own tasks. asynchronous

  2.2.3 introduction to Axios

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Axios test</title>
		<script src="../js/axios.js"></script>
	</head>
	<body>
		<h1>Axios Test case-1</h1>
		<script>
			/* 
				1.You can edit Axios to send ajax requests
				2.There is a "cross domain" problem when sending ajax requests between different servers
				3.Solve cross domain problems by annotation. @ CrossOrigin  
			 */
			var url = "http://localhost:8080/hello"
			axios.get(url)
				 .then(function(result){ //Callback function!!!
					 console.log(result)
				 })
		</script>
	</body>
</html>

  2.2.4 editing UserController

  2.2.5 page effect display

  3. Front and rear end interaction cases

3.1 Axios get request

3.1.1 description of business requirements

Requirement: query user information according to ID
URL address: http://localhost:8080/axios/getUserById?id=100
Parameter: id = 100
Return value: the JSON of the User object forges a User object

3.1.2 editing AxiosController  

package com.jt.controller;

import com.jt.pojo.User;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin    //It mainly solves cross domain problems
@RequestMapping("/axios")
public class AxiosController {
    /**
     * URL Address: http://localhost:8080/axios/getUserById?id=100
     * Parameter: id = 100
     * Return value: the JSON of the User object forges a User object
     */
    @RequestMapping("/getUserById")
    public User getUserById(Integer id){
        //Query database by ID
        User user = new User();
        user.setId(id);
        user.setName("study hard");
        user.setAge(1000);
        user.setSex("male");
        return user;
    }
}

3.1.3 edit page HTML

/**
			 * var Keyword has no concept of scope!!!!
			 * let Equivalent to var has scope and is more secure
			 * const Defining constants
			 * Description of axios data return value object:
			 * 		axios In order to receive the data from the back-end server, the promise object is used
			 * 		Packaging parameters
			 */
			let url1 = "http://localhost:8080/axios/getUserById?id=100"	
			axios.get(url1)
				 .then(function(promise){
					 console.log(promise.data)
				 })

3.1.4 editing page effect

  3.2 Axios get object parameter writing method

3.2.1 description of business requirements

Requirement: query user information according to ID
URL address: http://localhost:8080/axios/getUserByNA?id=xxx&name=xxxx
Parameter: id=xxx name=xxx
Return value: List [user1,user2]

3.2.2 editing UserController  

 /**
     * URL Address: http://localhost:8080/axios/getUserByNA?id=xxx&name=xxxx
     * Parameter: id = XXX name = XXX
     * Return value: List [user1,user2]
     */
    @RequestMapping("/getUserByNA")
    public List<User> getUserByNA(User user){
        List<User> list = new ArrayList<>();
        list.add(user);//Simplified assignment operation returns directly
        list.add(user);
        return list;
    }

3.2.3 edit page JS

/**
			 * 1.get Request object parameters
			 * 2.Syntax description:
			 * 		Keywords: params: object information
			 */
			let user2 = {name:"tomcat",age:100}
			let url2 = "http://localhost:8080/axios/getUserByNA"
			axios.get(url2,{params:user2})
				 .then(function(promise){
					 console.log(promise.data)
				 })

3.2.4 page effect display

1. Page URL address

2. Page printing information  

3.3 Axios get restful structure  

3.3.1 requirements description

Users who query name=tomcat sex = "male" require restFul style for data acquisition
URL address: http://localhost:8080/axios/findUserByNS/tomcat/ male
Parameter: name/sex
Return value: List

3.3.2 editing AxiosController  

 /**
     * URL Address: http://localhost:8080/axios/findUserByNS/tomcat/ male
     * Parameter: name/sex
     * Return value: List < user >
     */
    @RequestMapping("/findUserByNS/{name}/{sex}") //Call the set method to assign a value to the property
    public List<User> findUserByNS(User user){
        List<User> list = new ArrayList<>();
        list.add(user);
        list.add(user);
        return list;
    }

3.3.3 edit front-end JS

/**
				 * Requirements: use restFul style to realize front - end and back - end interaction
				 * URL:  http://localhost:8080/axios/findUserByNS/tomcat/male
				 * Difficulties:
				 * 		1.tomcat/Men write directly in the url address. It is inconvenient to expand later
				 * Template string writing: a new function introduced by ES6
				 * Syntax:
				 * 		1. Use backquotes``
				 * 		2. Function: 1. It can ensure the format of string
				 * 				  2.The value of the variable can be obtained dynamically
				 */ 
				let user3 = {name: "tomcat", sex: "male"}
				let url3 = `http://localhost:8080/axios/findUserByNS/${user3.name}/${user3.sex}`
				let html = `<div>
								<p>AAA</p>
								<p>BBB</p>
							</div>
							`
				axios.get(url3)
					 .then(function(promise){
						 console.log(promise.data)
					 })

3.3.4 page effect display

1. Page URL address

  2. Page data display

 

Keywords: css3 html css

Added by lordzardeck on Wed, 01 Dec 2021 16:15:45 +0200