Mastering Spring Boot Request Mapping: Content Types, Params, Headers, and Dynamic Registration
This guide explains how to use Spring Boot's @GetMapping attributes to restrict requests by content type, parameters, and headers, compares PathPattern and AntPathMatcher URI patterns, and demonstrates dynamic registration of request handlers through programmatic mapping configuration.
Environment
Spring Boot version 2.4.11.
Consumable Content Types
You can narrow request mapping by the request's Content-Type. Example:
@GetMapping(consumes = MediaType.TEXT_HTML_VALUE)
public Object html() {
return "html";
}
@GetMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public Object json() {
return "json";
}The html endpoint matches requests with Content-Type=text/html, while the json endpoint matches Content-Type=application/json.
Producible Content Types
Similarly, you can restrict the response format with produces:
@GetMapping(produces = MediaType.TEXT_HTML_VALUE)
public Object html() {
return "<h1>html</h1>";
}
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public Object json() {
return "json";
}The html endpoint is selected when the request's Accept=text/html, and the json endpoint when Accept=application/json.
Matching Parameters or Headers
Requests can be filtered by query parameters:
@GetMapping(path = "/params", params = {"name=ak"})
public Object params() {
return "params";
}This method matches only when the request contains name=ak.
Or by request headers:
@GetMapping(path = "/headers", headers = {"token=123"})
public Object headers() {
return "headers";
}This method matches when the header token=123 is present.
URI Pattern Matching
Spring MVC offers two pattern‑matching strategies:
PathPattern : a pre‑parsed, web‑optimized pattern that handles encoding and path variables efficiently. It is the recommended choice for Spring WebFlux and, from Spring 5.3 onward, can be enabled for Spring MVC.
AntPathMatcher : the original string‑based matcher used for class‑path and file‑system resources; it is slower and less robust with encoded URLs.
Both support the same syntax, including wildcards ( *, **) and variable captures such as {project} or {project:[a-z]+}. Example patterns:
/resources/ima?e.png – matches a single character in a segment
/resources/*.png – matches zero or more characters in a segment
/resources/** – matches multiple segments
/projects/{project}/versions – captures a path variable
/projects/{project:[a-z]+}/versions – captures with a regular expression
Pattern Comparison
When several patterns match a URL, Spring selects the most specific one. Specificity is determined by counting URI variables (1 point), single wildcards (1 point), and double wildcards (2 points). Ties are broken by pattern length, then by preferring variables over wildcards. The default catch‑all pattern ( /**) is always lowest priority.
Dynamic Registration of Request Handlers
You can register handlers programmatically without declaring them as beans:
@Service
public class UserHandler {
@ResponseBody
public Object getUsers(@PathVariable("id") String id, HttpServletRequest request) {
System.out.println(request);
return "查询用户ID为: " + id;
}
}Configuration to register the above method:
@Configuration
public class MappingConfig {
@Autowired
public void setHandlerMapping(RequestMappingHandlerMapping mapping, UserHandler handler) throws NoSuchMethodException {
RequestMappingInfo info = RequestMappingInfo.paths("/users/{id}").methods(RequestMethod.GET).build();
Method method = UserHandler.class.getMethod("getUsers", String.class, HttpServletRequest.class);
mapping.registerMapping(info, handler, method);
}
}Create a RequestMappingInfo object containing the basic metadata.
Obtain the Method object of the handler.
Register the mapping with RequestMappingHandlerMapping.
Done!
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
