Mastering Spring MVC Request Mapping: Annotations, URI Patterns, and Media Types
This guide explains how to use Spring MVC's @RequestMapping and its shortcut annotations, choose between PathPattern and AntPathMatcher for URI matching, configure suffix and media type handling, and customize request mapping with parameters, headers, and programmatic registration.
Overview
You can use the @RequestMapping annotation to map requests to controller methods, with attributes for URL, HTTP method, parameters, headers, and media types. Shortcut annotations like @GetMapping , @PostMapping , @PutMapping , @DeleteMapping , and @PatchMapping are specialized variants for specific HTTP methods.
URI Patterns
@RequestMapping can map using URL patterns. Two options are available:
PathPattern – a pre‑parsed pattern designed for web use, handling encoding and path variables efficiently.
AntPathMatcher – a string‑based matcher used historically in Spring MVC; less efficient and more error‑prone with encoded URLs.
PathPattern is the recommended solution (also the only option in Spring WebFlux) and can be enabled in MVC configuration for Spring 5.3+. It supports the same syntax as AntPathMatcher and adds capture patterns like {*spring} and limited use of ** at the end of a pattern.
Example patterns:
"/resources/ima?e.png" – matches a single character in a path segment
"/resources/*.png" – matches zero or more characters in a segment
"/resources/**" – matches multiple path segments
"/projects/{project}/versions" – captures a variable
"/projects/{project:[a-z]+}/versions" – captures with a regex
URI variables are accessed with @PathVariable :
<code>@GetMapping("/owners/{ownerId}/pets/{petId}")
public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
// ...
}</code>Variables can be declared at class and method levels:
<code>@Controller
@RequestMapping("/owners/{ownerId}")
public class OwnerController {
@GetMapping("/pets/{petId}")
public Pet findPet(@PathVariable Long ownerId, @PathVariable Long petId) {
// ...
}
}</code>Type conversion is automatic; mismatches raise TypeMismatchException . Custom converters can be registered via DataBinder .
Suffix Matching
Since Spring 5.3, the default .* suffix pattern matching is disabled, so URLs like /person.pdf no longer map to /person . Content negotiation should rely on the Accept header instead of file extensions.
To re‑enable suffix matching in older versions, set useSuffixPatternMatching(false) and favorPathExtension(false) in PathMatchConfigurer and ContentNegotiationConfigurer . If extensions must be used, limit them via the mediaTypes property.
Consumer Media Types
Use the consumes attribute to narrow mapping by request Content‑Type :
<code>// Only accepts JSON payloads
@PostMapping(path = "/pets", consumes = "application/json")
public void addPet(@RequestBody Pet pet) {
// ...
}</code>Negated expressions (e.g., !text/plain ) exclude specific types. Class‑level consumes can be overridden by method‑level declarations.
MediaType provides constants such as APPLICATION_JSON_VALUE and APPLICATION_XML_VALUE .
Producer Media Types
Use the produces attribute to narrow mapping by the response Accept header:
<code>// Returns JSON when the client accepts it
@GetMapping(path = "/pets/{petId}", produces = "application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId) {
// ...
}</code>Negated expressions work similarly. Class‑level produces can be overridden by method‑level settings.
Request Parameters and Headers
Mapping can be restricted by request parameters:
<code>// Matches only when myParam equals myValue
@GetMapping(path = "/pets/{petId}", params = "myParam=myValue")
public void findPet(@PathVariable String petId) {
// ...
}</code>Headers can be matched in the same way:
<code>// Matches only when myHeader equals myValue
@GetMapping(path = "/pets", headers = "myHeader=myValue")
public void findPet(@PathVariable String petId) {
// ...
}</code>HTTP Request Methods
@GetMapping (or @RequestMapping(method = HttpMethod.GET) ) automatically supports HTTP HEAD. OPTIONS is handled by returning the allowed methods in the Allow header. It is recommended to declare the specific HTTP method for each handler.
Custom Annotations
Spring MVC allows composite annotations meta‑annotated with @RequestMapping , such as @GetMapping , @PostMapping , etc., to narrow the attribute set. Advanced custom mapping can be achieved by extending RequestMappingHandlerMapping and overriding getCustomMethodCondition to return a custom RequestCondition .
Programmatic Registration
Handlers can be registered programmatically for dynamic scenarios:
<code>@Configuration
public class MyConfig {
@Autowired
public void setHandlerMapping(RequestMappingHandlerMapping mapping, UserHandler handler) throws NoSuchMethodException {
RequestMappingInfo info = RequestMappingInfo.paths("/user/{id}").methods(RequestMethod.GET).build();
Method method = UserHandler.class.getMethod("getUser", Long.class);
mapping.registerMapping(info, handler, method);
}
}</code>Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.