In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article focuses on "how to use Spring MVC to achieve RESTful style", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let the editor take you to learn "how to use Spring MVC to achieve RESTful style"!
Implementing RESTful style RESTful with SpringMVC
The Chinese definition is "state transition of the presentation layer", which is not a standard, but a design style.
Its main function is to make full use of the characteristics of HTTP protocol and standardize the URI path of resource acquisition.
Generally speaking, RESTful-style design allows parameters to be passed to the server through URL splicing, in order to make URL look more concise and practical.
And for different operations, specify different HTTP methods (POST/GET/PUT/DELETE). It can be said that as long as it is an application or design with the relevant conditions and principles mentioned above, it can be called a RESTful-style application.
A program or design that satisfies RESTful should meet the following conditions and constraints:
First: standardize the requested URL. There are no verbs in URL, but verbs that use HTTP protocol.
Second: make full use of the HTTP method. HTTP method names include: GET, POST, PUT, PATCH, DELETE
Using Spring MVC to implement RESTful style
Spring mvc can use the path setting of @ RequestMapping, combined with the parameter specification of @ PathVariable, to implement RESTful-style requests.
To implement the sample, a RESTful-style request is implemented by splicing the id of a fruit product, and the request is sent to the background to obtain fruit data in JSON format.
@ RequestMapping (value= "/ queryFruit/ {id}", method= {RequestMethod.GET}) public @ ResponseBody Fruits getFruitById (Model model,@PathVariable ("id") Integer fruitId) throws Exception {Fruits fruit = fruitsServices.queryFruitById (fruitId); return fruit;}
In this method, a dynamic data "{id}" is added to the request path of the @ RequestMapping annotation, which parses the foreground request path and parses the location of the dynamic data into a request parameter named id.
@ PathVariable annotation, in which the key name of the request parameter is specified and mapped on the parameter defined later. Here, the fruitId shape parameter is defined to receive the request parameter named id. Finally, the @ ResponseBody annotation plus the previously configured type converter is used to return the fruit details of the JSON type on the client side. Generally speaking, the realization of RESTful style using SprngMVC mainly lies in the mapping of request path and request parameters, as well as the designation of RequestMapping. Change the contents of the configuration file in web.xml by changing * .do to "/" so that RESTful-style requests written can be intercepted and parsed by the front-end controller.
Springmvc /
Then restart the project and enter the URL: http://localhost:8080/ project name / queryFruit/1
The above code is the request code of query type, while the requests for adding, modifying, and deleting are similar, except that you need to specify different RequestMethod (POST/PUT/DELETE). The sample code is as follows:
/ / add fruit logic @ RequestMapping (value= "/ addFruit", method= {RequestMethod.POST}) public String addFruit (Model model,Fruits fruit) throws Exception {/ / implements return "..." } / / Delete the fruit product @ RequestMapping (value= "/ deleteFruit/ {id}", method= {RequestMethod.DELETE}) public String deleteFruitById (Model model,@PathVariable Integer fruitId) throws Exception {/ / implements return "..." via id. } / / modify fruit commodity information @ RequestMapping (value= "/ editFruit", method= {RequestMethod.PUT}) public String editFruitById (Model model,Fruits fruit) throws Exception {/ / implements return "...";}
The frontend needs to configure the method (method parameter) of the HTTP request when accessing the RESTful-style add and delete requests. If you are using form form submission on a JSP page to request a RESTful-style service, you need to specify the relevant method parameters of the HTTP request in the form form tag, depending on the type of request.
Static resource access problem
Previously, a RESTful-style DispatcherServlet front-end controller filter was configured in web.xml. However, this filtering method will cause the problem that static resources cannot be accessed, such as placing a picture logo.jpg under the image folder under webContent.
As the picture is placed outside the WEB-INF file (due to the protection mechanism of JavaWEB, the files under the WEB-INF folder are not directly accessible), in principle, you can access the picture directly by accessing static resources, but enter the project name of http://localhost:8080/ / image/logo.jpg request, can not get the picture resources.
Reason:
The request filtering mechanism of the front-end controller is configured in web.xml. In order to receive RESTful-style requests, the filtered suffix is removed and becomes a request path that filters all suffixes. In this case, the static resource will be processed by the front-end controller as a business request, and the front-end controller does not find a Controller controller method that can handle the request, so it throws a 404 error.
Solution 1:
Use "mvc:resources" to configure the resolution path of the static resource in the class loading configuration file springmvc, configure the URI path of the static resource that needs to be loaded in the label, and then configure the real resource path mapped by the URI.
When the parsing path of the static resource file is configured in the springmvc.xml, the front-end controller will map the true path of the static resource according to the specific subpath in the request URL, and then feedback the real static resource information for the front-end.
Solution 2:
Use "" in springmvc.xml to configure the default Servlet processor, which defines a DefaultServletHttpRequestHandler in the SpringMVC context, which filters requests entering the DispatcherServlet. If it finds a request that has not been mapped, the request is handed over to the default Servlet of the Web application server. If it is not a request for static resources, the DispatcherServlet front-end controller continues to process it. At this point, the static resources in the request can be processed separately from other business requests, thus returning static resource information normally.
What does Spring MVC's RESTful learn about RESTful?
RESTful, also known as REST (Representational State Transfer), can be understood as a software architecture style or design style.
The RESTful style is a style of programming request paths with request parameters.
For example, a traditional URL request is as follows:
Http://.../requestparam?id=1
With RESTful style, the URL request becomes:
Http://.../param/1
RESTful style uses put,delete,post and get methods in HTTP requests to correspond to add, delete, modify and query operations, respectively. However, at present, domestic developers only use post and get to achieve add, delete, modify and search operations.
Use a simple addition to calculate @ Controllerpublic class RestFulController {/ / RestFul: localhost:8080/add/a/b @ RequestMapping (value = "/ add/ {a} / {b}", method = RequestMethod.GET) public String test (@ PathVariable int a miner PathVariable int b, Model model) {int res = a + b; model.addAttribute ("msg", "result:" + res) Return "test";}} Title$ {msg}
At this point, I believe you have a deeper understanding of "how to use Spring MVC to achieve RESTful style", might as well come to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.