Spring MVC path parameters and JSON parameter reception

1. Path parameter reception

Path passing parameters is a way of passing parameters in the URL path. In RESTful web applications, path passing parameters are often used to represent unique identifiers of resources or more complex representations. The Spring MVC framework provides the @PathVariable annotation to handle path passing parameters.

The @PathVariable annotation allows mapping placeholders in the URL to parameters in controller methods.

For example, if we want to map the {id} under the /user/{id} path to a parameter of the controller method, we can use the @PathVariable annotation to achieve this.

The following is an example of using the @PathVariable annotation to handle path parameters:

 /**
 * Dynamic path design: /user/{dynamic part}/{dynamic part}   Dynamic part use{}Just include! {}Internal dynamic identification!
 * Formal parameter list value: @PathVariable Long id  If the formal parameter name = {Dynamic identification} automatic assignment!
 *              @PathVariable("Dynamic identification") Long id  If the formal parameter name != {Dynamic identification} You can assign a value by specifying a dynamic identifier!
 *
 * access test:  /param/user/1/root  -> id = 1  uname = root
 */
@GetMapping("/user/{id}/{name}")
@ResponseBody
public String getUser(@PathVariable Long id, 
                      @PathVariable("name") String uname) {
    System.out.println("id = " + id + ", uname = " + uname);
    return "user_detail";
} 

Notice:

  • If no value is specified in @PathVariable, the formal parameter name must be the same as the dynamic identifier in the dynamic path.
  • If the formal parameter name is different from the dynamic identifier in the dynamic path, then you need to specify the same value as the dynamic identifier in @PathVariable.

2. json parameter reception

When the front-end passes JSON data, the Spring MVC framework can use the @RequestBody annotation to convert the JSON data into Java objects. The @RequestBody annotation indicates that the value of the current method parameter should be obtained from the request body, and the value attribute needs to be specified to indicate which parameter the request body should be mapped to. Its usage and sample code are as follows:

  1. Example of front-end sending JSON data:
    {
      "name": "Zhang San",
      "age": 18,
      "gender": "male"
    } 
    
  2. Define a Java class for receiving JSON data, for example:
    public class Person {
      private String name;
      private int age;
      private String gender;
      // getter and setter slightly
    } 
    
  3. In the controller, use the @RequestBody annotation to receive the JSON data and convert it into a Java object, for example:
    @PostMapping("/person")
    @ResponseBody
    public String addPerson(@RequestBody Person person) {
    
      // available here person objects to operate on JSON Properties included in the data
      return "success";
    } 
    

In the above code, the @RequestBody annotation maps the JSON data in the request body to the person parameter of type Person, and passes it as an object to the addPerson() method for processing.

Notice:

  • Java itself does not support json data type processing
  • If you need to process json data in Java, you need to configure a json type processing tool (jackson)

3 jackson configuration method

  1. Springmvc handlerAdpater configures the json converter. The configuration class needs to be clear:
 //TODO: SpringMVCConfiguration class corresponding to the component [statementSpringMVCRequired component information]

  //TODO: importhandlerMappingandhandlerAdapterthree ways
   //1.Automatic importhandlerMappingandhandlerAdapter [recommend]
   //2.No need to add,springmvcWill check if configuredhandlerMappingandhandlerAdapter,No configuration is loaded by default
   //3.use@Beanmode configurationhandlerMapperandhandlerAdapter
  @EnableWebMvc  //jsondata processing,This annotation is required,Because he will joinjsonprocessor
  @Configuration
  @ComponentScan(basePackages = "com.atguigu.controller") //TODO: conductcontrollerscanning

  //WebMvcConfigurer springMvcSpecifications for configuring components,Configure components,Provide various methods! Can be realized in the early stage
  public class SpringMvcConfig implements WebMvcConfigurer {
  } 
  1. Add jackson dependency to pom.xml
 <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.15.0</version>
    </dependency> 

@EnableWebMvc can help us accomplish three things:

  • Add handlerMapping to ioc container
  • Add handlerAdapter to ioc container
  • Add jackson converter and jackson conversion object method