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

Dkwestworld 2021-06-23 21:57:24
source code analysis use rest


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);
}

 

版权声明
本文为[Dkwestworld]所创,转载请带上原文链接,感谢
https://javamana.com/2021/06/20210623215610642z.html

  1. redis cluster如何支持pipeline
  2. How does redis cluster support pipeline
  3. 上海 | 人英网络 | 招Java开发25-35K、React前端开发25-40K
  4. Shanghai | Renying network | recruit java development 25-35k, react front end development 25-40k
  5. SpringCloud+Docker+Jenkins+GitLab+Maven实现自动化构建与部署实战
  6. Spring cloud + docker + Jenkins + gitlab + Maven to realize automatic construction and deployment
  7. 性能工具之linux三剑客awk、grep、sed详解
  8. Performance tools of Linux three swordsmen awk, grep, sed
  9. 一次“不负责任”的 K8s 网络故障排查经验分享
  10. An "irresponsible" experience sharing of k8s network troubleshooting
  11. 性能工具之linux三剑客awk、grep、sed详解
  12. Performance tools of Linux three swordsmen awk, grep, sed
  13. 使用Spring Data JPA 访问 Mysql 数据库-配置项
  14. Accessing MySQL database with spring data JPA - configuration item
  15. 一次“不负责任”的 K8s 网络故障排查经验分享
  16. An "irresponsible" experience sharing of k8s network troubleshooting
  17. 注册中心ZooKeeper,Eureka,Consul,Nacos对比
  18. Linux最常用的指令大全!快看看你掌握了吗?
  19. Comparison of zookeeper, Eureka, consult and Nacos
  20. Linux most commonly used instruction encyclopedia! Let's see. Do you have it?
  21. Matrix architecture practice of Boshi fund's Internet open platform based on rocketmq
  22. 字节面试,我这样回答Spring中的循环依赖,拿下20k offer!
  23. Byte interview, I answer the circular dependence in spring like this, and get 20K offer!
  24. oracle 11g查看alert日志方法
  25. How to view alert log in Oracle 11g
  26. 手写Spring Config,最终一战,来瞅瞅撒!
  27. Handwritten spring config, the final battle, come and see!
  28. 用纯 JavaScript 撸一个 MVC 框架
  29. Build an MVC framework with pure JavaScript
  30. 使用springBoot实现服务端XML文件的前端界面读写
  31. Using springboot to read and write the front interface of server XML file
  32. 【Javascript + Vue】实现随机生成迷宫图片
  33. [Javascript + Vue] random generation of maze pictures
  34. 大数据入门:Hadoop伪分布式集群环境搭建教程
  35. Introduction to big data: Hadoop pseudo distributed cluster environment building tutorial
  36. 八股文骚套路之Java基础
  37. commons-collections反序列化利用链分析(3)
  38. Java foundation of eight part wensao routine
  39. Analysis of common collections deserialization utilization chain (3)
  40. dubbogo 社区负责人于雨说
  41. Yu Yu, head of dubbogo community, said
  42. dubbogo 社区负责人于雨说
  43. Yu Yu, head of dubbogo community, said
  44. 设计模式 选自《闻缺陷则喜》此书可免费下载
  45. The design pattern is selected from the book "you are happy when you hear defects", which can be downloaded free of charge
  46. xDAI被选为 Swarm 的侧链解决方案,将百倍降低 Swarm 网络Gas费
  47. L2 - 深入理解Arbitrum
  48. Xdai is selected as the side chain solution of swarm, which will reduce the gas cost of swarm network 100 times
  49. L2 - deep understanding of arbitrum
  50. Java全栈方向学习路线
  51. 设计模式学习04(Java实现)——单例模式
  52. Java full stack learning route
  53. Design pattern learning 04 (Java implementation) - singleton pattern
  54. Mybatis学习01:利用mybatis查询数据库
  55. Mybatis learning 01: using mybatis to query database
  56. Java程序员从零开始学Vue(01)- 前端发展史
  57. Java程序员从零开始学Vue(05)- 基础知识快速补充(html、css、js)
  58. Java programmers learn Vue from scratch
  59. Java programmers learn Vue from scratch (05) - quick supplement of basic knowledge (HTML, CSS, JS)
  60. 【Java并发编程实战14】构建自定义同步工具(Building-Custom-Synchronizers)