Spring MVC mapping HTTP requests to Controller
The core of the request map: @RequestMapping annotation
@RequestMapping
It is the most core and general mapping annotation in Spring MVC. It can be used for class-level and method-level.
-
Class-level Mapping:
- when
@RequestMapping
When applied to a class, it defines the base class URL path for the Controller to handle all requests. - This avoids adding duplicate same path prefix on each method.
- when
-
Method-level Mapping:
- when
@RequestMapping
When applied to a method, it specifies which (or which) URL path the method handles specifically. - This path is relative to the class level path (if it exists).
- when
@RequestMapping’s main properties:
-
value
orpath
:- Specifies the mapped URL path. It can be an array of strings that represent mapping multiple paths to the same method.
- Support Ant-style path modes (e.g.
*
,**
,?
) and URI template variables (path variables, such as{userId}
)。 -
value
andpath
It is a synonym and can be used interchangeably.
-
method
:- Specifies the HTTP request method (GET, POST, PUT, DELETE, PATCH, OPTIONS, HEAD, TRACE) processed by this method.
- It can be one
RequestMethod
An array of enumerated values indicates that multiple HTTP methods are processed. - If not specified, the default match will be matched.allHTTP method.
-
params
:- Map based on request parameters (Query Parameters or Form Data). The match will be successful only if the specified parameter is included (or does not contain, or has a specific value) in the request.
- Expression syntax:
-
"myParam"
: ParametersmyParam
Must exist. -
"!myParam"
: ParametersmyParam
It must not exist. -
"myParam=myValue"
: ParametersmyParam
Must exist and the value ismyValue
。 -
"myParam!=myValue"
: ParametersmyParam
Must exist and the value is notmyValue
。 - Multiple conditions can be combined, such as
{"myParam=val", "otherParam"}
(AND relationship).
-
-
headers
:- Map according to request headers. The match will be successful only if the request contains (or does not contain, or has a specific value) the header specified.
- Syntax and
params
Similar, such as"Accept=application/json"
,"!User-Agent"
,"X-Custom-Header=value"
。
-
consumes
:- Specify the request that this method can handle
Content-Type
(i.e. the data type sent by the client). Only when requestedContent-Type
The mapping will be successful only when the header matches the specified value. - For example:
consumes = "application/json"
orconsumes = MediaType.APPLICATION_JSON_VALUE
. Multiple options can be specified, such as{"application/json", "application/xml"}
。
- Specify the request that this method can handle
-
produces
:- Specify the response that this method can generate
Content-Type
(i.e. the data type returned by the server). Spring will requestAccept
Header conducts content negotiation with this property (Content Negotiation) and select the most suitable oneHttpMessageConverter
Serialize the return value. - For example:
produces = "application/json"
orproduces = MediaType.APPLICATION_JSON_VALUE
. Multiple can be specified.
- Specify the response that this method can generate
Example: Use @RequestMapping
import ; import .*; import ; @Controller @RequestMapping("/users") // Class-level mapping, all methods are in the /users pathpublic class UserController { // Map GET /users/{id} @RequestMapping(value = "/{id}", method = , produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody // If you use @Controller, you need to add this to return the data public User getUser(@PathVariable Long id) { // ... Get user logic ... return new User(id, "Example User"); } // Mapping POST /users @RequestMapping(method = , consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public String createUser(@RequestBody User newUser) { // ... Create user logic ... return "User created"; } // Map GET /users?admin=true (requires admin parameter) @RequestMapping(method = , params = "admin=true") @ResponseBody public String getAdminUsers() { // ... Get the administrator user list ... return "List of Admin Users"; } // Map GET /users (only accepts JSON requests) @RequestMapping(method = , headers = "Accept=application/json") @ResponseBody public String getUsersAcceptingJson() { // ... Get the user list ... return "List of Users (JSON requested)"; } }
@RequestMapping Variation (Shortcut Annotation)
To improve the readability and simplicity of your code, Spring provides shortcut annotations for specific HTTP methods. They are essentially@RequestMapping
Presetmethod
Aliases for attributes.
-
@GetMapping
: Map HTTP GET requests. Equivalent to@RequestMapping(method = )
。 -
@PostMapping
: Map HTTP POST requests. Equivalent to@RequestMapping(method = )
。 -
@PutMapping
: Map HTTP PUT requests. Equivalent to@RequestMapping(method = )
。 -
@DeleteMapping
: Map HTTP DELETE requests. Equivalent to@RequestMapping(method = )
。 -
@PatchMapping
: Map HTTP PATCH requests. Equivalent to@RequestMapping(method = )
。
These shortcut annotations are also supported@RequestMapping
ofvalue
/path
, params
, headers
, consumes
, produces
Attributes.
Advantages of using shortcut annotations:
- More concise: The code is shorter.
- More clear: You can see at a glance what kind of HTTP request the method is dealing with.
Example: Use shortcut annotation (@RestController simplified)
import .*; import ; @RestController // Using @RestController, no need to add @ResponseBody to each method@RequestMapping("/api/items") // Class level mappingpublic class ItemController { // Map GET /api/items/{itemId} // producers can also write strings directly @GetMapping(value = "/{itemId}", produces = MediaType.APPLICATION_JSON_VALUE) public Item getItem(@PathVariable String itemId) { // ... Get item logic ... return new Item(itemId, "Sample Item"); } // Mapping POST /api/items // consumers can specify multiple @PostMapping(consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) public String createItem(@RequestBody Item newItem) { // ... Create item logic ... return "Item created: " + (); } // Mapping PUT /api/items/{itemId} @PutMapping("/{itemId}") public Item updateItem(@PathVariable String itemId, @RequestBody Item updatedItem) { // ... Update item logic ... (itemId); // Assume that the update is successful return updatedItem; } // Mapping DELETE /api/items/{itemId} @DeleteMapping("/{itemId}") public String deleteItem(@PathVariable String itemId) { // ... Delete item logic ... return "Item deleted: " + itemId; } // Mapping GET /api/items?type=gadget @GetMapping(params = "type=gadget") public String getGadgets() { return "List of Gadgets"; } // Map GET /api/items (requires specific header) @GetMapping(headers = "X-API-Version=2") public String getItemsV2() { return "List of Items (API V2)"; } } // Example Pojoclass Item { private String id; private String name; // constructors, getters, setters... public Item(String id, String name) { = id; = name; } public String getId() { return id; } public void setId(String id) { = id; } public String getName() { return name; } public void setName(String name) { = name; } } class User { private Long id; private String username; // constructors, getters, setters... public User(Long id, String username) { = id; = username; } public Long getId() { return id; } public String getUsername() { return username; } }
Summarize
-
@RequestMapping
is the basics, can map any HTTP method and provide the most comprehensive configuration options (path
,method
,params
,headers
,consumes
,produces
)。 -
@GetMapping
,@PostMapping
,@PutMapping
,@DeleteMapping
,@PatchMapping
It is a shortcut for specific HTTP methods, making the code more concise and clear. It is currently under Spring MVC/WebFlux development.recommendusage. - Can beClass LevelandMethod LevelAt the same time, using mapping annotations, the basic path is defined at the class level and the relative path is defined at the method level.
-
URL pathpass
value
orpath
Attribute matching, support pattern and path variables ({var}
)。 -
HTTP Methodspass
method
Attributes (in@RequestMapping
) or select a specific shortcut annotation (such as@GetMapping
) to match. -
Request parameterspass
params
Make attributes to match. -
Request headerpass
headers
Make attributes to match. -
Request body type (
Content-Type
)passconsumes
Make attributes to match. -
Acceptable response type (
Accept
)passproduces
Attributes participate in content negotiation.
The above is the detailed content of the Spring MVC mapping HTTP request to Controller. For more information about Spring MVC mapping HTTP to Controller, please pay attention to my other related articles!
Related Articles
Getting started with Mockito unit testing in SpringBoot
Unit tests are used in many places. This article mainly introduces the introduction to the Mockito unit test in SpringBoot, which has certain reference learning value for everyone's study or work. Friends who need it, please learn with the editor below.2021-06-06Java Design Pattern Understand the Responsibility Chain Model from the Risk Control Chain
This article mainly introduces the detailed explanation of the Java design model from the risk control chain to understand the responsibility chain model. Friends in need can refer to it for reference. I hope it can be helpful. I wish you more progress and get promoted as soon as possible to get a salary increase as soon as possible.2023-05-05Analysis of the execution process of for loop in Java
This article mainly introduces the execution process of for loops in Java, and analyzes the execution principle and order of for loops in an example. It has certain reference value for a deep understanding of Java. Friends who need it can refer to it.2015-02-02Detailed explanation of Java concurrent programming prevents deadlock process
This article mainly introduces a detailed explanation of the Java concurrent programming process to prevent deadlocks. The article introduces the example code in detail, which has certain reference value for everyone's learning or work. Friends who need it can refer to it.2019-11-11Solve the problem of error reporting by tool interface call: error:Unsupported Media Type
When an "UnsupportedMediaType" error is encountered, it means that the Content-Type of the HTTP request does not match the server's expectations. For example, the server expects to receive JSON format data and sends a plain text format. Common Content-Type types include text/html, application/json, multipart/form-data, etc.2024-10-10Detailed explanation of WebSocket solutions under Spring Cloud microservice architecture
This article mainly introduces a detailed explanation of the WebSocket solution under the Spring Cloud microservice architecture. The editor thinks it is quite good. I will share it with you now and give you a reference. Let's take a look with the editor2018-12-12A brief discussion on the implementation of cache processing of SpringBoot integrated Redis (Spring AOP implementation)
This article mainly introduces a brief discussion on SpringBoot integrated Redis implementation cache processing (Spring AOP implementation). The editor thinks it is quite good. I will share it with you now and give you a reference. Let's take a look with the editor2017-12-12Java generates QR code with logo and text
This article mainly introduces Java's method of generating QR codes with logo and text, helping everyone better understand and learn to use Java. Interested friends can learn about it.2021-04-04Detailed explanation of deep and shallow copy of Java Cloneable interface
This article mainly introduces the deep and shallow copy of the Java Cloneable interface in detail. The sample code in the article is introduced in detail and has certain reference value. Interested friends can refer to it. I hope it can help you.2022-03-03Springboot project parameter verification method (Validator)
This article introduces how to use the `spring-boot-starter-validation` package and annotation to implement request parameter verification in Spring Boot project. It mainly introduces the use of verification annotation, the exception capture of verification failed, and the grouping function of `@Validated`2025-02-02