Cgb2005 - Jingtao 16 (cross domain: jsonp CORS, the single sign on system accesses the user name data through cross domain, validates the static code block interface document, quickly locate the page according to the URL, httpclient)

Cool breeze AAA 2022-02-13 07:43:14 阅读数:380

cgb2005 cgb jingtao cross domain

matters needing attention

1. A description of cross domain
Cross domain testing The same-origin policy Cross domain approach :jsonp(get request ) cors
jsonp: Be careful url Format , Splice callback function name callback Browser caching strategy random number
jsopp Optimize — adopt Ajax Send request after encapsulation
spring For jsonp To return data in a specific format, you need to splice strings manually Optimize ---- Through one Api Object splicing string
cors The essence is Ajax, Mainstream browsers support the need to define configuration classes .
2. Jingtao single sign on System ( No page , hit jar package )
Sign in / register General page Jump —resful style
Enter the user name... On the registration page , When the cursor leaves, it will automatically verify whether there is data service – Static code block
according to url Quickly locate the page
Single sign on interface documentation ----- Check whether the data is available
Modify the global exception handling class
3 HttpClient
Concept : You can do it again java Code internal use httpClient launch http A tool that requests access to the server to obtain resources Api
Case test : Communication between servers 2 Kind of
Cross domain : Solve simple business problems , check
HttpClient: Complex business
HttpClient The shortcomings of .

1. A description of cross domain ( important )

1.1 Cross domain access testing

1.1.1 test 1: Test with the server ( General domain )

analysis :
1. Browser URL information : http://manage.jt.com/test.html
2. jax Requested address information : http://manage.jt.com/test.json
Conclusion :
When the browser address and ajax Requested address ( agreement :// domain name : port ) Phase at the same time , Normal business calls can be realized .

problem : Why do web addresses usually use domain names instead of ip Visit ?
On the Internet , Each machine and device will have a unique identifier ,IP Address . But memory IP Similar to the ID number, the address is also a long string of numbers , It's very inconvenient for people to remember . therefore , Domain name appears , Instead of complex IP Address , Convenient for us to quickly access the website .
therefore , When building a website online , First need to buy domain name .
And why do you pay for domain names , Because domain names are uniformly managed by the domain name Administration Bureau , Management costs , Such as technical cost 、 Labor cost, etc .

testing procedure :
1). Page code analysis .

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> test JSON Cross-domain problem </title>
<!-- introduce js Function class library -->
<script type="text/javascript" src="http://manage.jt.com/js/jquery-easyui-1.4.1/jquery.min.js"></script>
<!-- After introducing the class library js Code -->
<script type="text/javascript">
/* Document ready event function */
$(function(){

$.get("http://manage.jt.com/test.json",function(data){

alert(data.name);
})
})
</script>
</head>
<body>
<h1>JSON Cross domain request testing </h1>
</body>
</html>

 Insert picture description here

{
"id":"1","name":"tom"}

 Insert picture description here
2). Access to the effect .
 Insert picture description here

1.1.2 test 2: Different server tests ( Cross domain )

explain :
1. Browser URL information : http://www.jt.com/test.html
2.ajax Requested address information : http://manage.jt.com/test.json
Conclusion :
If the domain name and address are different, the request cannot get the response result normally .

step :
Put the same page (test.html) Put it in the front desk system , Start the foreground system and conduct the access test again ( Both front and rear platforms should be started ) It can be seen that... Cannot be sent Ajax request .
 Insert picture description here
 Insert picture description here

 Insert picture description here

1.2 Introduction to browser homology strategy

explain :
The browser is parsing ajax when , If you find that The requested protocol name :// Requested domain name : The port number of the request If the address is the same as that of the web address, it meets the provisions of the same origin policy , The browser can correctly parse the return value , The visit is called Same domain access , The strategy is called The same-origin policy . But if Violation of any one of the homology strategies , It's called Cross domain access , Browser for security reasons , Do not parse the return value .

Generalization : Browser parsing ajax when , Because the request violates the same origin policy, it is called cross domain request , The opposite is called homologous strategy .

 Insert picture description here
Be careful :
1).2 Key words : browser Ajax
2). Redirection is server resolution, so it is not cross domain .
 Insert picture description here

1.3 Common cross domain implementations 1–JSONP

1.3.1 JSONP The principle of cross domain implementation ( Difficult )

Ideas :
1. utilize javascrpit Medium src Property to implement cross domain requests .
2. Custom callback functions function callback(xxxx);
3. Encapsulate the result of return value in special format callback(json);
4. Due to the use of src Property to call therefore Can only support get Request type .

testing procedure :
1). page js edit :

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> test JSON Cross-domain problem </title>
<script type="text/javascript">
/*JS Is the language of interpretation and execution */
/* Define callback function */
function hello(data){

alert(data.name);
}
</script>
<!-- The json Save it to the browser and wait for it to be called , But you can't call without a function name -->
<script type="text/javascript" src="http://manage.jt.com/test.json"></script>
<script type="text/javascript" src="http://manage.jt.com/js/jquery-easyui-1.4.1/jquery.min.js"></script>
</head>
<body>
<h1>JS Cross-domain problem </h1>
</body>
</html>

 Insert picture description here
2). json data

hello({
"id":"1","name":"tom"})

 Insert picture description here
3). Start foreground Test again in the background ---- Successfully sent ajax request , Cross domain success .
 Insert picture description here

Step-by-step instructions :
1.javaScript Medium src Properties are not constrained by the same origin policy . Can get remote server data .

<!-- The json Save it to the browser and wait for it to be called , But you can't call without a function name namely , adopt src To call a call that you want others to call, you must have a name -->
<script type="text/javascript" src="http://manage.jt.com/test.json"></script>

2. Custom callback functions Any name Later, someone will help you encapsulate this function .

/* Define callback function */
function hello(data){

alert(data.name);
}

3. Will return the value result Special format encapsulation callback(JSON); callback: Callback function

hello({
"id":"1","name":"tomcat cat "})

1.3.2 JSONP Concept

JSONP(JSON with Padding) yes JSON A kind of “ Usage mode ”, It can be used to solve the problem of cross-domain data access in major browsers . Because of the homology strategy , Generally speaking, it is located in server1.example.com The web page can't and isn't server1.example.com Server communication , and HTML Of

1.3.3 JSONP Optimize – adopt Ajax encapsulate

explain : utilize js Of script Labeled src Attribute is inconvenient to initiate a request , You need to customize the callback function , Encapsulating the return value in a special format is too troublesome , How to simplify the steps ?
answer : Can be encapsulated as ajax Call mode ( The underlying principle has not changed ).

1.3.3.1 Compile the page and send ajax request

Ajax Call mode analysis : Use and common ajax The same way .
1). page js

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSONP test </title>
<script type="text/javascript" src="http://manage.jt.com/js/jquery-easyui-1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){

alert(" Test access begins !!!!!")
$.ajax({

url:"http://manage.jt.com/web/testJSONP",
type:"get", //jsonp Can only support get request 
dataType:"jsonp", //dataType Represents the return value type ( Must be specified as jsonp, Otherwise it will become ordinary Ajax call )
//jsonp: "callback", // Specify the parameter name 
//jsonpCallback: "hello", // Specify the callback function name 
success:function (data){
 //data after jQuery Encapsulation return is json strand 
console.log(data);
//alert(data.id);
//alert(data.name);
// Convert to string using 
//var obj = eval("("+data+")");
//alert(obj.name);
}
});
})
</script>
</head>
<body>
<h1>JSON Cross domain request testing </h1>
</body>
</html>

 Insert picture description here
2). request url Of 2 A special parameter analysis .
 Insert picture description here
callback: Specify the callback function name , It needs to be consistent with the name of the specific return value encapsulated , The implementation steps are : stay url Add one more parameter after the address , Represents the callback function name , The default name is callback=xxxxxxxxxxxx Random generation . And send the dynamically generated name as a parameter to the background server , After that, the parameter name is dynamically resolved during data acquisition , Finally, it is spliced into callback+json Structure .

random number : Because of the browser cache policy , If the second party sends the same request, it will go through the cache . However, if the business data is changed for the second time, the executed request is still the original cache, which is obviously inappropriate , So it's usually in js Splice a random number that does not affect the business logic to distinguish different requests .

3).callback=xxxxxx Parameter names and value You can specify the value of .

 Insert picture description here
 Insert picture description here

1.3.3.2 Editing backstage Controller Return the data

This is a web Sent request to access manage The server
 Insert picture description here

package com.jt.web.controller;
import com.jt.pojo.ItemDesc;
import com.jt.util.ObjectMapperUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class JSONPController {

/** * Test whether the cross domain access is successful * url Address : http://manage.jt.com/web/testJSONP?callback=jQuery111106536880527642785_1600138715329&_=1600138715330 * Parameters : No one can not answer , Because I will splice one by myself every time callback, The return value also needs to be encapsulated by the method name , So it can be passed directly as a parameter . * The returned value should be data encapsulated in a special format . callback(JSON) */
@RequestMapping("/web/testJSONP")
public String jsonp(String callback){

ItemDesc itemDesc = new ItemDesc();// Compile return value data 
itemDesc.setItemId(100L).setItemDesc(" The cross domain test was successful !!!!");
String json = ObjectMapperUtil.toJSON(itemDesc);// Object to json
return callback+"("+json+")";
}
}

1.3.3.3 Optimize string splicing ---- Re edit Controller

package com.jt.web.controller;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.jt.pojo.ItemDesc;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class JSONPController {

/** Optimize manual splicing, writing and sending : * Test whether the cross domain access is successful * url Address : http://manage.jt.com/web/testJSONP?callback=jQuery111106536880527642785_1600138715329&_=1600138715330 * The returned value should be data encapsulated in a special format . callback(JSON) * JSONPObject Parameter description : * 1.function Callback function name * 2. The returned object can then be converted to JSON */
@RequestMapping("/web/testJSONP")
public JSONPObject jsonp(String callback){
 //spring Provided 
ItemDesc itemDesc = new ItemDesc();
itemDesc.setItemId(100L).setItemDesc("API test !!!");
return new JSONPObject(callback, itemDesc);
}
}

 Insert picture description here

1.3.3.4 Access test

 Insert picture description here
Console output :
 Insert picture description here

1.3.4 principle

 Insert picture description here

1.4 Common cross domain implementations 2–CORS Cross domain approach

1.4.1 CORS Cross domain description

explain : The current mainstream browsers support by default cors Cross domain form , But you need the server to add the response information , Otherwise, the browser does not support data acquisition .
HEAD、GET、POST
 Insert picture description here

1.4.2 edit CORS Configuration class (common)

If anyone wants to cross domain, just put it in that project , Because it is used more, it is placed in common in .
 Insert picture description here

package com.jt.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CORSConfig implements WebMvcConfigurer {

/** * On the back end To configure cors Policies that allow access * Method statement : * 1.addMapping(/**) What kind of requests can be allowed across domains : /* Represents the primary directory /** All directories representing all requests * 2.allowedMethods("*") Define request types that allow cross domain : * On behalf of all * 3.allowedOrigins("*") Allow that website to access :* The representative can allow any domain name , Writing a specific website can only represent one * 4.allowCredentials(true) Whether it is allowed to carry across domains cookie Equal parameter * 5.maxAge(1800) Set request long link timeout ( Before cross domain, you will ask whether cross domain is allowed ) */
@Override
public void addCorsMappings(CorsRegistry registry) {
// Identifier of the allowed policy 
registry.addMapping("/**")
.allowedMethods("GET","POST")
.allowedOrigins("*")
.allowCredentials(true)
.maxAge(1800);//30 minute 
}
}

1.4.3 cors Cross domain testing

stay web The foreground sends a request to the background , If you can access it, it means cross domain success .
1). page js
 Insert picture description here

2).JSON data format
 Insert picture description here
3). Access test
 Insert picture description here

1.4.4 Summary of cross domain

1).jsonp
jsonp Nature uses javaScript Medium src Attribute get Cross domain of request implementation .
The return value must be encapsulated in a special format .
2).cors
cors The essence is Ajax, Server side strategy .
You need to add response header information on the server , Specify which servers are allowed access to .

2. Jingtao single sign on System

2.1 General page Jump

2.1.1 Business analysis

Requirement specification : explain : When the user clicks login / When the register button Need to jump to the specified page .
 Insert picture description here
 Insert picture description here

 Insert picture description here
 Insert picture description here
1. Logon url Address

http://www.jt.com/user/login.html

2. Registered url Address

http://www.jt.com/user/register.html

2.1.2 edit UserController(web In the project )

 Insert picture description here

package com.jt.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller // Due to the design of page jump function .
@RequestMapping("/user")
public class UserController {

/** * General page Jump implementation * 1.http://www.jt.com/user/login.html login.jsp page * 2.http://www.jt.com/user/register.html register.jsp page * restFul The way : 1. Get dynamic url Parameters in , After that, the general jump is implemented . */
@RequestMapping("/{moduleName}")
//resful The style needs to be annotated 
public String module(@PathVariable String moduleName){

return moduleName;
}
}

2.1.3 Page effect display

Click login again register
 Insert picture description here
 Insert picture description here

2.2 establish JT-SSO project

2.2.1 JT-SSO Project description

effect : Mainly for jt-web The server provides support for user data , When it comes to user Of CRUD All operations should be completed by the system .
packaging : jar Package , There is no page support in this project .
matters needing attention : Inherit jt/ rely on jt-common Add the plug-in .
Port number : 8093
 Insert picture description here

2.2.2 Create project (Maven)

 Insert picture description here

2.2.3 edit pom.xml The configuration file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>jt-sso</artifactId>
<!-- The default packaging method is jar So it doesn't matter if you don't write -->
<!-- Add inheritance -->
<parent>
<artifactId>jt</artifactId>
<groupId>com.jt</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<!-- Add dependency -->
<dependencies>
<dependency>
<groupId>com.jt</groupId>
<artifactId>jt-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<!-- Add the plug-in -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

2.2.4 edit User Of POJO object (common)

 Insert picture description here

package com.jt.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.experimental.Accessors;
@TableName("tb_user")
@Data
@Accessors(chain = true)
public class User extends BasePojo {

@TableId(type = IdType.AUTO) // The primary key increases automatically 
private Long id;
private String username; // user name 
private String password; // password need md5 encryption 
private String phone; // Telephone 
private String email; // mailbox The registration page does not have this option Temporarily use the phone instead of email 
}

2.2.5 Realization JT-SSO The code structure

 Insert picture description here
demand : adopt sso.jt.com/findUserAll Request , Get all the records in the user table json String return .

1). Add main startup class :
 Insert picture description here


package com.jt;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.jt.mapper")// Add package scan 
public class SpringBootRun {

public static void main(String[] args) {

SpringApplication.run(SpringBootRun.class, args);
}
}

2). The configuration file
 Insert picture description here

server:
port: 8093
servlet:
context-path: /
spring:
datasource:
# introduce druid data source
#type: com.alibaba.druid.pool.DruidDataSource
#driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/jtdb?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
username: root
password: root
mvc:
view:
prefix: /WEB-INF/views/
suffix: .jsp
#mybatis-plush To configure
mybatis-plus:
type-aliases-package: com.jt.pojo
mapper-locations: classpath:/mybatis/mappers/*.xml configuration: map-underscore-to-camel-case: true logging: level: com.jt.mapper: debug 

3). Control layer :
 Insert picture description here

package com.jt.controller;
import com.jt.pojo.User;
import com.jt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {

@Autowired
private UserService userService;
/** * To complete the test * 1.url Address :findUserAll * 2. Parameters :null * 3. Return value :List<User> */
@RequestMapping("/findUserAll")
public List<User> findUserAll(){

return userService.findUserAll();
}
}

4).service Interface
 Insert picture description here

package com.jt.service;
import com.jt.pojo.User;
import java.util.List;
public interface UserService {

List<User> findUserAll();
}

5).service Interface implementation class
 Insert picture description here

package com.jt.service;
import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService{

@Autowired
private UserMapper userMapper;
@Override
public List<User> findUserAll() {

return userMapper.selectList(null);
}
}

6).mapper Interface
 Insert picture description here

package com.jt.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jt.pojo.User;
public interface UserMapper extends BaseMapper<User> {

}

2.2.6 By domain name sso.jt.com Implement access

1). modify nginx After the restart nginx The server .
 Insert picture description here

# build jt-sso The server
server {

listen 80;
server_name sso.jt.com;
location / {

proxy_pass http://localhost:8093;
}
}

2). edit hosts file
 Insert picture description here
3). Configure the main startup class access test
 Insert picture description here

 Insert picture description here

2.3 Analysis of user data verification

2.3.1 Business needs

explain : When a user is registering , If enter one user name , It should be directed to jt-sso A single sign on system initiates a request , Verify the existence of user data , If it exists, the user will be prompted .
 Insert picture description here

2.3.2 Single sign on service interface document

explain : This is about... In the single sign on service interface document Check whether the data is available .
 Insert picture description here

2.3.3 page url analysis

explain : There are interface documents, and the code can be developed , But here, as a learning front desk, you also need to understand .
1). When the user name is entered, the cursor leaves , Will send a request for validation .
 Insert picture description here
2).URL explain
 Insert picture description here

2.3.4 Search page JS

explain : adopt url Locate the dead address to the specific page that sent the request
step :
1). Copy url Fixed address in .
 Insert picture description here
2). stay idea Search in the project :ctrl+h eclipse Key position
Then the number of lines you want to jump +enter key
 Insert picture description here

2.3.5 page JS analysis

 Insert picture description here

 $.ajax({

url : "http://sso.jt.com/user/check/"+escape(pin)+"/1?r=" + Math.random(),
dataType : "jsonp",
success : function(data) {
 // State information :200 success State information :201 Failure 
checkpin = data.data?"1":"0";
if(data.status == 200){

if (!data.data) {

validateSettings.succeed.run(option);
namestate = true;
}else {

validateSettings.error.run(option, " The user name is already occupied !");
namestate = false;
}
}else{

// Identify the abnormal operation of the background server 
validateSettings.error.run(option, " The server is busy , Please later !!!( I reported a mistake backstage, and I don't know what's wrong !!!)");
namestate = false;
}
}
});

2.2.6 edit jt-sso Of UserController

explain :
1). from web Send a request to the single sign on server sso Get data in .
2).SysResult The object is already in common Medium vo I wrote about .

package com.jt.controller;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.jt.pojo.User;
import com.jt.service.UserService;
import com.jt.vo.SysResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/user")// The business name should be written on the class 
public class UserController {

@Autowired
private UserService userService;
/** * Business description : jt-web Server acquisition jt-sso data JSONP Cross-domain request * url Address : http://sso.jt.com/user/check/{param}/{type} * Parameters : param: Data to be verified type: The type of verification * Return value : SysResult object * The actual return value : callback(SysResult Of JSON) */
@RequestMapping("/check/{param}/{type}")// Parameters are written on the path resful Style acquisition 
public JSONPObject checkUser(@PathVariable String param,
@PathVariable Integer type,
String callback){

/** * The interface document requires a return value of : * { * status: 200 //200 success ,201 We didn't find out * msg: “OK” // Return message * data: false // Return the data true The user already exists ,false The user doesn't exist , Sure * } * And the system vo---SysResult Return the result in the original format : * { * status: //200 success 201 Failure * msg: // Server prompts success Failure * data: // The server returns value data . * } * It can be seen that the requirements here are data Return to one boolean Value of type, not data . */
boolean flag = userService.checkUser(param,type);
SysResult.success(flag);
// Because cross domain requires special return value format , So further encapsulation is needed spring Optimized string splicing, writing and sending : Connect directly through this object 
return new JSONPObject(callback, SysResult.success(flag));
}
/** * To complete the test * 1.url Address :findUserAll * 2. Parameters :null * 3. Return value :List<User> */
@RequestMapping("/findUserAll")
public List<User> findUserAll(){

return userService.findUserAll();
}
}

 Insert picture description here

2.2.7 edit jt-sso Of UserService

package com.jt.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class UserServiceImpl implements UserService{

@Autowired
private UserMapper userMapper;
// Definition map Sets are assigned through static code blocks .
private static Map<Integer,String> columnMap = new HashMap<>();
static {

columnMap.put(1, "username");
columnMap.put(2, "phone");
columnMap.put(3, "email");
}
/** * The basis of judgment : Query according to user name If it turns out >0 The user already exists . * namely : If you query according to the user name, the record whose return value is the query represents * This data exists , And don't care who it is . * @param param Data to be verified * @param type The type of verification 1username 2phone 3 email 6789910 * @return */
@Override
public boolean checkUser(String param, Integer type) {

/** * 1. Need to put type Type into Specific field information 1=username 2=phone 3=email * explain : Because what the user passes in is 1 2 3 Such specific figures , The database inventory is based on these numbers * Expected fields , Therefore, it is necessary to perform conversion query . * 2. How to efficiently transform ??? * If we use ordinary if Judge switch Judge that the performance is too low ---- You can use static code blocks , It exists when the class is loaded . * * */
String column = columnMap.get(type);
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq(column, param);
Integer count = userMapper.selectCount(queryWrapper);// The result It's worth it 1 It's just not worth it 0
return count > 0 ? true :false;// yes 1 Greater than 0 Represents that there is a value to return true Already exists yes 0 No more than 0 Indicates that no value is returned false No user exists 
}
@Override
public List<User> findUserAll() {

return userMapper.selectList(null);
}
}

 Insert picture description here

2.2.8 Page effect test

explain : start-up web sso The server , because admin123 The database exists, so as long as the cursor leaves, it will prompt the user that it has been occupied .
 Insert picture description here

2.2.9 Modify the global exception handling mechanism

Problem specification :
When Back end ( Not backstage , Represents all servers ) Error in server execution , Global exception handling is performed . however JSONP The call requirements of the request for return type callback(JSON) structure . So we need to reconstruct the return value structure type of global exception handling .
Before the refactoring :
 Insert picture description here

After refactoring :
 Insert picture description here

package com.jt.aop;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.jt.vo.SysResult;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
//@ControllerAdvice // Intercept controller layer ( because mapper Layer and the service The layer anomaly is finally thrown to controller layer , So the interception control layer is the most appropriate .)
//@ResponseBody Interaction with pages is json Data of type 
@RestControllerAdvice // Defines the class for handling global exceptions AOP= Abnormal notice ( The bottom layer is encapsulated )
public class SystemAOP {

/** * Methods for defining global exceptions When something goes wrong , Program start execution The parameters are general class type * If something goes wrong , You should output abnormal information , Then return the error data . * * Rules for solving cross domain global exception handling : Cross domain of Jingtao project is to use JSONP. http://xxxx?callback=xxxxx * So if the request carries callback Parameters Think it is JSONP Cross-domain request . * difficulty : How to get callback What about parameters? ?? * Generally, in the control layer, you can use HttpServletRequest( Request header object ) obtain url Parameters carried in . * Ideas : * Because this class will be used in case of exceptions in the whole project , So according to url Do you carry it callback Judge , * If there is callback Exception handling methods that should return cross domain failures , without callback The parameter represents the method that returns normal request exception handling failure . */
@ExceptionHandler({
RuntimeException.class}) // Multiple different types of exceptions ( Such as io,sql), How to write it :{RuntimeException.class,xxx,xxx}
public Object systemAop(Exception e, HttpServletRequest request){

e.printStackTrace();
String callback = request.getParameter("callback");
if (StringUtils.isEmpty(callback)) {

// Normal method call mode 
return SysResult.fail();
} else {

// Prove to be jsonp Cross-domain request 
return new JSONPObject(callback, SysResult.fail());
}
}
}

Access test : Because the modification is common So the back-end servers have to be restarted .
 Insert picture description here
 Insert picture description here

3 HttpClient

3.1 Business needs

Business description : For some operations, data may be processed , After that, communication is formed between the server and the server .eg: Users need to pay for things they buy online , The background execution process of payment is , The user accesses the server of the payment page through the browser Process the data , Then send the data to the bank's server , Finally, the bank server returns the result .

Why process data ??
Because the bank server requires the format of some parameters when receiving some data . Directly through the cross domain method, these data are written in js It's inconvenient in the car . solve : The user sends a request through the browser to the background server for processing , The background server processes the data internally , Then it is transmitted to the bank server remotely .

Can cross domain be solved ??
You can't , Cross domain is resolved through the browser ajax request , That is, directly access the bank server through the browser , Data cannot be processed , Banks can't accept these ordinary data formats , So cross domain can't solve the problem . Cross domain because data cannot be processed , The account password will be exposed during transmission , unsafe .
 Insert picture description here
summary :
1). Cross domain access can only solve some simple problems, such as : check
Execute the process : The front-end server sends ajax request ( Through page js), After being parsed by the browser, it is sent to the back-end server for calling (controller—service----mapper The hierarchical call returns data ).
2).httpClient Remote calls are more secure , You can process the data and then send the request
Execute the process : Sent by the front-end code ajax The request goes through the local server for parameter processing (controller–service), Pass the processed parameters to the background server for calling (controller–service–mapper).

 Insert picture description here

3.2 HttpClient Introduce

HTTP The agreement may be now Internet Most used on 、 The most important agreement , More and more Java Applications need to go directly through HTTP Protocol to access network resources . Although in JDK Of java net Access is already provided in the package HTTP Basic functions of the protocol , But for most applications ,JDK The functions provided by the library itself are not rich and flexible enough .HttpClient yes Apache Jakarta Common Sub projects under , To provide efficient 、 Abreast of the times 、 Feature rich support HTTP Client programming toolkit for protocol , And it supports HTTP Latest version and suggestions of the agreement .HttpClient It has been applied in many projects , such as Apache Jakarta Two other open source projects famous in Cactus and HTMLUnit It's all used HttpClient. Now? HttpClient The latest version is HttpClient 4.5 .6(2015-09-11)

summary : stay java Agent internal have access to httpClient launch http Request access to the server for resources .( Tools API)

3.3 HttpClient Introductory cases

Be careful : In the future SpringCloud There will be more advanced Api Yes HttpClient Of Api encapsulate , This more advanced Api The bottom is HttpClient Of Api.

3.3.1 Import jar package

<!-- add to httpClient jar package -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>

 Insert picture description here

3.3.2 Introductory cases (web Inside )

 Insert picture description here

package com.jt.test;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import java.io.IOException;
public class TestHttpClient {

/** * requirement : stay java Inside the code , Get Baidu's page . * Implementation steps : * 1. Determine the target address : https://www.baidu.com/ * 2. establish httpClient Client object * 3. Create request type * 4. launch http request . And get the result of the response . Then judge whether the status code is 200 If it is equal to 200 The request is correct ( Because the request may not succeed ) * 5. If the request is correct, the response value information is obtained dynamically . After that, the data is processed again .... * */
@Test
public void test01(){

//1. Determine the address 
String url = "https://www.baidu.com/";
//2. Create a default request object Pay attention to the guide bag apache
HttpClient httpClient = HttpClients.createDefault();
//3. Create request type send out get request :HttpGet post:HttpPost put:HttpPut
HttpGet get = new HttpGet(url);
try {

//3.1 Perform the requested , Because requests don't necessarily ‘ send out ’ success , So you need to handle exceptions try-catch/throws, The return value is HttpResponse
HttpResponse httpResponse = httpClient.execute(get);
//4. Judge whether the status code is correct Because the request may not succeed 
int statusCode = httpResponse.getStatusLine().getStatusCode();//4.1 Get status code 
if(statusCode == 200){
 //4.2 The request is correct 
//4.3 Get all the response information of the server (json/html/xml/xxxx)
HttpEntity httpEntity = httpResponse.getEntity();
//4.4 Generally, this entity object will be converted into a string and used , When converting, you need to specify the code Otherwise, it will be disorderly 
String result = EntityUtils.toString(httpEntity,"UTF-8");
//5. After obtaining the business processing, you can execute it ......
System.out.println(result); // What you get should be a page , The essence of a page is html
}else{

// If the request is unsuccessful, print the status code information .
System.out.println(httpResponse.getStatusLine().getStatusCode());
}
} catch (IOException e) {

e.printStackTrace();
}
}
}

Result of operation :
 Insert picture description here

3.4. HttpClient Strengthen the case

3.4.1 Requirement specification :

Users use the web address http://www.jt.com/getItems requirement use httpClient The way , obtain jt-manage Product information in , after json In the form of strings .
jt-web Server access jt-manage When the website http://manage.jt.com/getItems.

3.4.2 Editor's desk HttpClientController(web)

 Insert picture description here

package com.jt.controller;
import com.jt.pojo.Item;
import com.jt.service.HttpClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class HttpClientController {

@Autowired
private HttpClientService httpClientService;
/** * Get back end manage Product data information in */
@RequestMapping("/getItems")
public List<Item> getItems(){

return httpClientService.getItems();
}
}

3.4.3 Editor's desk HttpClientService(web)

 Insert picture description here

package com.jt.service;
import com.jt.pojo.Item;
import com.jt.util.ObjectMapperUtil;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service
public class HttpClientServiceImpl implements HttpClientService{

@Override
public List<Item> getItems() {

// The front end accesses the back end java Internal code can only pass through httpclient The way 
List<Item> itemList = new ArrayList<>();// Prepare the set to be converted into an object 
//1. Define the remote access URL 
String url = "http://manage.jt.com/getItems";
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
try {

HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode() == 200){

String result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
/** * result yes jt-manage by jt-web Back to List<Item> Of JSON strand , * And now what needs to be returned is List<Item> A collection of types, so you need to convert */
if(!StringUtils.isEmpty(result)){
// It can only be processed if it is not empty 
itemList = ObjectMapperUtil.toObject(result, itemList.getClass());
}
}
} catch (IOException e) {

// Output the exception information to the console 
e.printStackTrace();
// Turn the check type exception into a run-time exception throw 
throw new RuntimeException(e);
}
return itemList;
}
}

3.4.5 Editing backstage HttpClientController(manage)

 Insert picture description here

package com.jt.web.controller;
import com.jt.pojo.Item;
import com.jt.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class HttpClientController {

@Autowired
private ItemService itemService;
/** * url Request address : http://manage.jt.com/getItems */
@RequestMapping("/getItems")
public List<Item> getItems(){

return itemService.getItems();
}
}

3.4.6 Editing backstage HttpClientService(manage)

 Insert picture description here

 @Override
public List<Item> getItems() {

return itemMapper.selectList(null);
}

3.4.7 Page effect display

 Insert picture description here

3.5 HttpClient Call disadvantages

shortcoming : There are many levels of code calls , How to simplify ?
answer : SOA( Service Oriented Architecture ).
 Insert picture description here

copyright:author[Cool breeze AAA],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130743061163.html