• 周日. 11月 27th, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

[source code analysis] – do you use rest style to process requests in springboot?

[db:作者]

1月 6, 2022

Catalog

Preface

1、 What is? REST style

1.1  resources (Resources)

1.2  The presentation layer (Representation)

1.3  State transformation (State Transfer)

1.4  review

2、 Practice SpringBoot Realization REST Style form submission

2.1    Not REST Style code

2.2   REST Style code

3、 Source code analysis

3.1 Springboot How to deal with it

3.2 HiddenHttpMethodFilter Handle PUT and DELETE


Preface

In the job, in the interview , It’s always mentioned REST style ?

But will you really use it ? Do you know how to modify the underlying configuration ?

Is it lost in the complicated business code ? …

1、 What is? REST style

A lot of blogs explaining concepts , Personal feeling Ruan Yifeng The most thorough ,

Link to the original text  https://blog.csdn.net/zhangliangzi/article/details/51428171 

This link is not original , To prevent him from deleting the article , I pick up the essence ,

First RESTful framework , Is the most popular Internet software architecture . Its structure Clear 、 Meet the standard 、 Easy to understand 、 Easy to expand , So more and more websites are using .

REST The word , yes  Roy Thomas Fielding  In his 2000 Year of Doctoral Dissertation Proposed in .

REST, namely  Representational State Transfer  Abbreviation , If an architecture conforms to REST principle , Call it RESTful framework .

To understand RESTful framework , The best way is to understand Representational State Transfer What exactly does this phrase mean , What does each of its words mean . If you understand the name , It’s not hard to understand REST What kind of design is it .

 

1.1  resources (Resources)

REST The name of ” Represent layer state transformation ” in , Omit the subject .” The presentation layer ” In fact, it means ” resources “(Resources) Of ” The presentation layer “.

So-called ” resources “, It’s an entity on the Internet , Or a specific information on the Internet . It can be a piece of text 、 A picture 、 A song 、 A service , In a word, it is a concrete reality . You can use one URI( Uniform resource locator ) Pointing to it , Each resource corresponds to a specific URI. To get this resource , Visit its URI Can , therefore URI It becomes the address or unique identifier of each resource .

So-called ” surf the internet “, With a series of Internet ” resources ” Interaction , Call it the URI.

 

1.2  The presentation layer (Representation)

” resources ” It’s an information entity , It can have many external forms . We put ” resources ” In the form of , It’s called it ” The presentation layer “(Representation).

such as , The text can be used txt Format representation , It can also be used. HTML Format 、XML Format 、JSON Format representation , It can even be in binary format ; Pictures can be used JPG Format representation , It can also be used. PNG Format representation .

URI Entities that represent resources only , Does not represent its form . Strictly speaking , Some of the last “.html” Suffixes are unnecessary , Because this suffix means format , Belong to ” The presentation layer ” Category , and URI It should only represent ” resources ” The location of . Its concrete manifestation , belong HTTP The requested header information uses Accept and Content-Type Field assignment , These two fields are right ” The presentation layer ” Description of .

 

1.3  State transformation (State Transfer)

Visit a website , It represents an interactive process between the client and the server . In the process , It’s bound to involve changes in data and state .

Internet communication protocol HTTP agreement , It’s a stateless protocol . It means , All States are saved on the server side . therefore , If the client wants to operate on the server , By some means , Let it happen on the server side ” State transformation “(State Transfer). And this transformation is based on the presentation layer , So is ” Represent layer state transformation “.

The means used by the client , Can only be HTTP agreement . say concretely , Namely HTTP In the agreement , Four verbs for operation :GET、POST、PUT、DELETE. They correspond to four basic operations :GET Used to obtain resources ,POST Used to create a new resource ( Can also be used to update resources ),PUT Used to update resources ,DELETE Used to delete resources .

 

1.4  review

Combine the above explanation , Let’s sum up what is RESTful framework :

(1) every last URI Represents a resource ;

(2) Between client and server , A layer of expression that conveys this resource ;

(3) Client through four HTTP Verb , Operate on the server-side resources , Realization ” Represent layer state transformation “.

The excerpt is over : I hope to know more about , Go to the original link above ( I hope he’s still )

reflection : I personally understand that in a word : It’s a way for the front end to get resources principle , This principle expresses the meaning of this request through purposeful verbs on the client side .

 

2、 Practice SpringBoot Realization REST Style form submission

 

2.1    Not REST Style code

Illustrate with examples : Operations on user tables , Add, delete, change and check the balance car. That’s what it says :

 @RequestMapping(value = "/getUser",method = RequestMethod.POST)
public String getUser(){
return "GET- Zhang San ";
}
@RequestMapping(value = "/saveUser",method = RequestMethod.POST)
public String saveUser(){
return "POST- Zhang San ";
}
@RequestMapping(value = "/putUser",method = RequestMethod.POST)
public String putUser(){
return "PUT- Zhang San ";
}
@RequestMapping(value = "/deleteUser",method = RequestMethod.POST)
public String deleteUser(){
return "DELETE- Zhang San ";
}

 

Each business has its own path , There are four different paths in the front end , The code as a whole looks redundant

 

2.2   REST Style code

@RequestMapping(value = "/user",method = RequestMethod.GET)
public String getUser(){
return "GET- Zhang San ";
}
@RequestMapping(value = "/user",method = RequestMethod.POST)
public String saveUser(){
return "POST- Zhang San ";
}
@RequestMapping(value = "/user",method = RequestMethod.PUT)
public String putUser(){
return "PUT- Zhang San ";
}
@RequestMapping(value = "/user",method = RequestMethod.DELETE)
public String deleteUser(){
return "DELETE- Zhang San ";
}

 

The obvious difference , The request path is unified , Get by request 、 Delete 、 modify 、 preservation Wait for the action , It’s much fresher

Since it’s so simple , Let’s practice it

The first 1 Step :application.propertities File configuration spring.mvc.hiddenmethod.filter.enable=true, To open the form REST Style support ( This source code analysis section will talk about )

The first 2 Ministry : Write a front-end page to test REST Style submission :

Notice that on the next page hidden Hide domain parameter details ( I’ll talk about it later in the source code section )

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1> test REST style </h1>
<form action="/user" method="get">
<input value="GET Submit " type="submit">
</form>
<form action="/user" method="post">
<input value="POST Submit " type="submit">
</form>
<form action="/user" method="post">
<input name="_method" type="hidden" value="PUT" />
<input value="PUT Submit " type="submit">
</form>
<form action="/user" method="post">
<input name="_method" type="hidden" value="DELETE" />
<input value="DELETE Submit " type="submit">
</form>
</body>
</html>
Click and drag to move 

 

Click on four buttons , Find that the jump is correct !

How he jumps , Look at source code analysis   ↓

 

3、 Source code analysis

 

3.1 Springboot How to deal with it

     SpringBoot The idea is : Since browsers can only send GET and POST request , You can use the parameters before and after , According to the agreed parameters , hold POST perhaps GET Turn directionally into PUT or DELETE request

 

3.2 HiddenHttpMethodFilter Handle PUT and DELETE

Realize to REST The support of request style mainly benefits from HiddenMethodFilter class , It’s also in WebMvcAutoConfiguration This autoconfiguration class is automatically injected when the project starts .

 // class WebMvcAutoConfiguration Next
// spring.mvc.hiddenmethod.filter.enabled by true Will load the filter , This explains the previous configuration items 

@Bean
@ConditionalOnMissingBean(HiddenHttpMethodFilter.class)
@ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled")
public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
return new OrderedHiddenHttpMethodFilter();
}

 Focus on HiddenHttpMethodFilter , seeing the name of a thing one thinks of its function hide HTTP Method filter , Its class notes are translated and pasted :

Because the browser only supports GET and POST, So a common technique ( for example Prototype The technology used by the library ) Is to use hidden form fields with additional ( _method ) Ordinary POST To pass on “ real ”HTTP Method . This filter reads the parameter and changes it accordingly HttpServletRequestWrapper.getMethod() Return value . Only “PUT” 、 “DELETE” and “PATCH” HTTP Method .
The name of the request parameter defaults to _method , But it can go through methodParam Attribute adjustment .

look down  HiddenHttpMethodFilter The core method of doFilterInternal() , How he parsed our hidden form

 // The core approach 
 @Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
HttpServletRequest requestToUse = request;
// First of all, it must be satisfied that POST Submit , Then hide the field name according to the form ”_method“ Parameters of 
if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
// obtain The name is ”_method“ Parameters of 
String paramValue = request.getParameter(this.methodParam);
// The obtained parameter is not empty 
if (StringUtils.hasLength(paramValue)) {
// Make the type name uppercase for us 
String method = paramValue.toUpperCase(Locale.ENGLISH);
// Only PUT DELETE PATCH
if (ALLOWED_METHODS.contains(method)) {
// Repackaging this type is POST Of request Be what the client wants it to be 
requestToUse = new HttpMethodRequestWrapper(request, method);
}
}
}
filterChain.doFilter(requestToUse, response);
}

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注