SoFunction
Updated on 2025-05-21

Spring MVC mapping HTTP requests to Controller

Spring MVC mapping HTTP requests to Controller

Updated: May 21, 2025 11:09:30 Author: Bingtangxin Study Room
Let's analyze in detail how to map HTTP requests to Controller's Handler Methods in Spring MVC, as well as how to use the @RequestMapping annotation. Friends who need it can refer to it

The core of the request map: @RequestMapping annotation

@RequestMappingIt is the most core and general mapping annotation in Spring MVC. It can be used for class-level and method-level.

  1. Class-level Mapping:

    • when@RequestMappingWhen 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.
  2. Method-level Mapping:

    • when@RequestMappingWhen 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).

@RequestMapping’s main properties:

  • valueorpath:

    • 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})。
    • valueandpathIt 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 oneRequestMethodAn 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": ParametersmyParamMust exist.
      • "!myParam": ParametersmyParamIt must not exist.
      • "myParam=myValue": ParametersmyParamMust exist and the value ismyValue
      • "myParam!=myValue": ParametersmyParamMust 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 andparamsSimilar, such as"Accept=application/json""!User-Agent""X-Custom-Header=value"
  • consumes:

    • Specify the request that this method can handleContent-Type(i.e. the data type sent by the client). Only when requestedContent-TypeThe 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"}
  • produces:

    • Specify the response that this method can generateContent-Type(i.e. the data type returned by the server). Spring will requestAcceptHeader conducts content negotiation with this property (Content Negotiation) and select the most suitable oneHttpMessageConverterSerialize the return value.
    • For example:produces = "application/json"orproduces = MediaType.APPLICATION_JSON_VALUE. Multiple can be specified.

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@RequestMappingPresetmethodAliases 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@RequestMappingofvalue/pathparamsheadersconsumesproducesAttributes.

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

  • @RequestMappingis the basics, can map any HTTP method and provide the most comprehensive configuration options (pathmethodparamsheadersconsumesproduces)。
  • @GetMapping@PostMapping@PutMapping@DeleteMapping@PatchMappingIt 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 pathpassvalueorpathAttribute matching, support pattern and path variables ({var})。
  • HTTP MethodspassmethodAttributes (in@RequestMapping) or select a specific shortcut annotation (such as@GetMapping) to match.
  • Request parameterspassparamsMake attributes to match.
  • Request headerpassheadersMake attributes to match.
  • Request body type (Content-Type)passconsumesMake attributes to match.
  • Acceptable response type (Accept)passproducesAttributes 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!

  • Spring
  • MVC
  • Mapping
  • HTTP Request
  • Controller

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-06
  • Java 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-05
  • Analysis 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-02
  • Detailed 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-11
  • Solve 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-10
  • Detailed 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 editor
    2018-12-12
  • A 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 editor
    2017-12-12
  • Java 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-04
  • Detailed 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-03
  • Springboot 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

Latest Comments