Spring boot handles annotations for request parameters

preface

In springboot, there are several annotations for processing url request parameters, which are:

@PathVariable, @ RequestHeader, @ RequestParam, @ MatrixVariable, @ RequestBody, let's learn today.

 

text

1,@RequestParam

@RequestParam can be used to assign the specified request parameter to the formal parameter in the method. The source code is as follows:

public @interface RequestParam {
  @AliasFor("name")
  String value() default "";
  @AliasFor("value")
  String name() default "";
  boolean required() default true;
  String defaultValue() default ValueConstants.DEFAULT_NONE;
}

 

It can be found that it has three properties:

  • value: request parameter name (must be configured)

  • Required: required. The default value is true, that is, the parameter must be included in the request. If it is not included, an exception will be thrown (optional configuration)

  • defaultValue: the default value. If this value is set, required will be automatically set to false. No matter whether you configure required or not and what value is configured, it will be false (optional configuration)

For example:

    @RequestMapping("/testequestparam")
    public String testequestParam(@RequestParam("name") String name){
        return name+",How do you do!";
    }

The output results are as follows:

 

 

 

The required parameter is required because it is true by default. If the request address is not followed by a parameter, an error will be reported:

 

 

 

If its value is set to false, the request succeeds, but the parameter value is null:

    @RequestMapping("/testequestparam1")
    public String testequestParam1(@RequestParam(value="name",required = false) String name){
        return name+",How do you do!";
    }

 

 

 

@RequestParam can also set the default value of a parameter for us when the parameter is empty:

    @RequestMapping("/testequestparam2")
    public String testequestParam2(@RequestParam(defaultValue = "defaultValue") String name){
        return name+",How do you do!";
    }

 

 

 

2,@PathVariable

@PathVariable is spring 3 A new function of 0 is used to receive the value of placeholder in the request path. The source code is as follows:

public @interface PathVariable {
  @AliasFor("name")
  String value() default "";
  @AliasFor("value")
  String name() default "";
  boolean required() default true;
}

Example:

    @GetMapping("/car/{id}/user/{name}/band/{band}")
    //http://localhost:8081/share/car/1/user/ Li Si / band / BYD/
    public String testPathVariable(@PathVariable("id") Integer id,
                                   @PathVariable("name") String name,
                                   @PathVariable("band")String band,
                                   @PathVariable Map<String,String> pv){
        return "The returned car is"+name+"Under my name id by"+id+"My car,What is the brand of the car"+band;
    }

 

The returned results are as follows:

 

 

@PathVariable supports returning all path variables:

    @GetMapping("/map/car/{id}/user/{name}/band/{band}")
    public Map<String,Object> testPathVariableMap(@PathVariable("id") Integer id,
                                                  @PathVariable("name") String name,
                                                  @PathVariable("band")String band,
                                                  @PathVariable Map<String,String> pv){
        Map<String,Object> map = new HashMap<>();
        map.put("id",id);
        map.put("name",name);
        map.put("band",band);
        map.put("pv",pv);
        return map;
    }

 

 

 

In addition, @ PathVariable also has the same attribute required as @ RequestParam, with the same usage, which will not be described here.

3,@RequestHeader

We know that a request will contain some first-class information, as follows:

 

 

 

@RequestHeader is to obtain the data in the request header, and obtain the parameter value specified in the request header by specifying the value of the parameter value. The source code is as follows:

public @interface RequestHeader {
 
  @AliasFor("name")
  String value() default "";

  @AliasFor("value")
  String name() default "";

  boolean required() default true;

  String defaultValue() default ValueConstants.DEFAULT_NONE;

}

Through the source code, you can find that the usage of other parameters is exactly the same as @ RequestParam. Example:

    @GetMapping("/map1/car/{id}/user/{name}/band/{band}")
    public Map<String,Object> testPathVariableMap1(@PathVariable("id") Integer id,
                                                   @PathVariable("name") String name,
                                                   @PathVariable("band")String band,
                                                   @PathVariable Map<String,String> pv,
                                                   @RequestHeader("User-Agent") String useragent,
                                                   @RequestHeader Map<String,String> header) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("name", name);
        map.put("band", band);
        map.put("pv", pv);
        map.put("useragent",useragent);
        map.put("header",header);
        return map;
    }

 

 

4,@MatrixVariable

@The MatrixVariabl annotation extends the function of URL request address. When using @ Matrixvariable annotation, multiple variables can be used; (semicolon) separation. This annotation allows developers to conduct multi condition combination query. Its source code is as follows:

public @interface MatrixVariable {
  @AliasFor("name")
  String value() default "";
  @AliasFor("value")
  String name() default "";
  String pathVar() default ValueConstants.DEFAULT_NONE;
  boolean required() default true;
  String defaultValue() default ValueConstants.DEFAULT_NONE;
}

It can be found that its attribute is basically the same as RequestParam, but there is an additional pathVar attribute, which represents the name of the URI path variable where the matrix variable is located. If necessary, disambiguation (for example, there are matrix variables with the same name in multiple path segments). Example:

    @GetMapping("/phone/{path}")
    public Map carsSell(@MatrixVariable("low") Integer low,
                        @MatrixVariable("band") List<String> brand,
                        @PathVariable("path") String path){
        Map<String,Object> map = new HashMap<>();

        map.put("low",low);
        map.put("brand",brand);
        map.put("path",path);
        return map;
    
}

It cannot be used directly with the previous annotation. It needs to be processed, because SpringBoot disables the function of matrix variables by default and needs to be started manually. The path processing is resolved through the UrlPathHelper. Removesemicoloncontent (remove semicolon content) supports matrix variables: write a configuration class here:

@Configuration(proxyBeanMethods = false)
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
        HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
        hiddenHttpMethodFilter.setMethodParam("_m");
        return hiddenHttpMethodFilter;
    }

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer){
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        //false means not to remove; Later, the matrix variable function can take effect
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
}

 

 

 

5,@RequestBody

@The RequestBody is mainly used to receive the data in the json string passed from the front end to the back end (the data in the request body); The most common way to use the request body to transfer parameters is undoubtedly the POST request, so when using @ RequestBody to receive data, it is generally submitted in the form of POST. The source code is as follows:

public @interface RequestBody {
    boolean required() default true;
}

The annotation has only one required attribute, which is true by default. Use the following:

    @PostMapping("/share/save")
    public Map postMethod(@RequestBody String content){
        Map<String,Object> map = new HashMap<>();
        map.put("content",content);
        return map;
    }

 

summary

The above are some annotations for request parameter processing in springboot. Through these annotations, we can obtain the parameters in the url and then carry out the corresponding business development processing.

 

Keywords: Spring Spring Boot

Added by socadmin on Wed, 19 Jan 2022 15:37:07 +0200