Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement RESTful style in SpringMVC

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you how to achieve the RESTful style of SpringMVC, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!

1. Introduction to RESTful

RESTful is the abbreviation of Representational State Transfer, which is defined as "state transition of presentation layer" in Chinese. RESTful is not a standard, but a design style.

RESTful is essentially an application layer solution for distributed systems. Its main function is to make full use of the characteristics of HTTP protocol and standardize the URL path of resource acquisition.

Generally speaking, the RESTful-style design allows parameters to be passed to the server through URL splicing, with the aim of making URL look more concise and practical. And different HTTP methods (POST/GET/PUT/DETELE) should be specified for different operations.

It can be said that as long as it is an application or design with the relevant constraints and principles mentioned above, it can be called a RESTful-style application.

2. SpringMVC implements RESTful style.

SpringMVC supports implementing RESTful-style requests. SpringMVC can use the path setting of the @ RequestMapping annotation, combined with the parameter specification of the @ PathVariable annotation, to implement RESTful-style requests.

[example] implement a Controller method that makes a RESTful-style request on the server.

/ * get user * * @ author pan_junbiao * / @ RequestMapping (value = "/ getUser/ {id}", method = RequestMethod.GET) @ ResponseBodypublic UserInfo getUserById (@ PathVariable ("id") int userId) {UserInfo userInfo = new UserInfo (); / / get user information if (userId = = 1) {userInfo.setUserId (1); userInfo.setUserName ("pan_junbiao 's blog") UserInfo.setBlogUrl ("https://blog.csdn.net/pan_junbiao"); userInfo.setRemark (" Hello, welcome to pan_junbiao 's blog ");} / / return the result return userInfo;} 2.1 @ PathVariable Note

In the above 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.

In the parameters of Controller, use the @ PathVariable annotation, where the key name of the request parameter is specified and mapped on the later defined parameter, where the userID parameter is defined to receive the request parameter named id.

The rest of the operation in the method body is the normal business logic, and finally the user information of the client JSON type is returned using the @ ResponseBody annotation plus the previously configured type converter.

Generally speaking, the implementation of RESTful style using SpringMVC mainly lies in the mapping of request path and request parameters, as well as the specification of RequestMethod.

2.2 modify the front-end controller configuration of SpringMVC

Previously, in the web.xml configuration file of the project project, the front-end controller of SpringMVC was configured to process requests centrally, as follows:

Springmvc org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:spring/spring-mvc.xml springmvc * .action

As you can see, the front-end controller filters the request path with the suffix "* .action", so the RESTful-style request written cannot be filtered and parsed by the front-end controller, so modify the configuration so that the RESTful-style request can be processed by the front-end controller of SpringMVC:

Springmvc /

Cause problem: this is modified to filter all request types to the front-end controller. This may lead to the problem of static resource access, which will be addressed below.

Execution result:

As can be seen from the execution results, the user information with id 1 is successfully queried, which indicates that the RESTful-style request service is written successfully.

3. Static resource access problem

Previously, a RESTful-style DispatcherServlet front-end controller filter was configured in web.xml to implement a mechanism for correctly handling RESTful-style requests. However, this filtering can cause problems that static resources cannot be accessed, such as creating a directory called img in the JavaWeb project and placing a picture named myImage.jpg in that directory.

Because the image is placed outside the WEB-INF folder (due to the protection mechanism of JavaWeb, the files under the WEB-INF folder cannot be accessed directly), in principle, the image can be obtained by directly accessing the static resources, but it is not found that the image resources can be obtained, as shown below:

Why is that? The reason is that the request filtering mechanism of the front-end controller configured in web.xml, in order to receive RESTful-style requests, removes the filtered suffix and becomes a request path that filters all suffixes. In this case, the static resource will be processed by the DispatcherServlet 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 (request resource not available) error.

If you want to handle static resources normally, but want to ensure a normal response to RESTful requests, you can solve it in the following two ways.

3.1 solution 1

Method 1, configure the resolution path of the static resource in the core configuration file of SpringMVC using the tag, configure the URI path of the static resource that needs to be loaded in the tag, and then configure the real resource path of the URI mapping. The configuration is as follows:

When the parsing path of the static resource file is configured in the core configuration file of the SpringMVC, the front-end controller will map the real 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.

3.2 solution II

The second method is to configure the default Servlet processor in the core configuration file of SpringMVC. The configuration will define a DefaultServletHttpRequestHandler in the SpringMVC context, which will screen the request entering the DispatcherServlet front-end controller. If it is found that the request is not mapped, the request will be 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 will continue to process.

At this point, the static resources in the request can be processed separately from other business requests, thus returning static resource information normally.

Execution result:

This shows that the static resource request is processed separately, which ensures that the RESTful request can be properly processed and responded by the Controller controller, and that the static resource can be obtained normally.

4. Comprehensive examples

The above code is the request code of query type, while the requests for adding, modifying, and deleting are similar, except that different RequestMethod attributes (POST/PUT/DELETE) need to be specified. The example code is as follows:

(1) create a user information entity class (UserInfo.java)

Package com.pjb.ssm.entity; / * user information entity class * * @ author pan_junbiao * * / public class UserInfo {private int userId; / / user ID private String userName; / / user name private String blogUrl; / / blog address private String remark; / / remarks / / omit getter and setter methods.}

(2) create a user information controller (UserController.java) to implement RESTful-style requests

Package com.pjb.ssm.controller; import com.pjb.ssm.entity.UserInfo;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody / * * user Information Controller * * @ author pan_junbiao * * / @ Controller@RequestMapping ("user") public class UserController {/ * get the user * * @ author pan_junbiao * / @ RequestMapping (value = "/ getUser/ {id}", method = RequestMethod.GET) @ ResponseBody public UserInfo getUserById (@ PathVariable ("id") int userId) {UserInfo userInfo = new UserInfo () / / get user information if (userId = = 1) {userInfo.setUserId (1); userInfo.setUserName ("pan_junbiao 's blog"); userInfo.setBlogUrl ("https://blog.csdn.net/pan_junbiao"); userInfo.setRemark (" Hello, welcome to pan_junbiao 's blog ") } / / return result return userInfo;} / * New user * / @ RequestMapping (value = "/ addUser", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;"}) @ ResponseBody public String addUser (UserInfo userInfo) {return "execute the new user, user name:" + userInfo.getUserName () } / * delete user * / @ RequestMapping (value = "/ deleteUser/ {id}", method = RequestMethod.DELETE, produces = {"text/html;charset=UTF-8;", "application/json;"}) @ ResponseBody public String deleteUser (@ PathVariable ("id") int userId) {return "delete user, user ID:" + userId } / * modify user * / @ RequestMapping (value = "/ updateUser", method = RequestMethod.POST, produces = {"text/html;charset=UTF-8;", "application/json;"}) @ ResponseBody public String updateUser (UserInfo userInfo) {return "perform modification user, user name:" + userInfo.getUserName ();}}

(3) create an execution page (index.jsp), in which the JQuery framework is used

Home page

/ / get the user button event $("# btnGetUser") .click (function () {var url = "${pageContext.request.contextPath} / user/getUser/1"; _ window.location.href = url;}) / / add user button event $("# btnAddUser") .click (function () {/ / execute Ajax request $.ajax ({type: "POST", url: "${pageContext.request.contextPath} / user/addUser", data: {userId: 1 UserName: "pan_junbiao 's blog"}, success: function (result) {$("# msg") .append (result + "

");}) / / Delete user button event $("# btnDeleteUser") .click (function () {/ / execute Ajax request $.ajax ({type: "DELETE", url: "${pageContext.request.contextPath} / user/deleteUser/1", success: function (result) {$("# msg") .append (result + ")

");}) / / modify user button event $("# btnUpdateUser") .click (function () {/ / execute Ajax request $.ajax ({type: "POST", url: "${pageContext.request.contextPath} / user/updateUser", data: {userId: 1 UserName: "pan_junbiao 's blog"}, success: function (result) {$("# msg") .append (result + "

");})

Execution result:

The above is all the content of the article "how to achieve RESTful style in SpringMVC". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report