Annotations for Springboot processing request parameters

Author platform:

| CSDN:blog.csdn.net/qq_41153943

| Nuggets: juejin.cn/user/651387…

| Zhihu: www.zhihu.com/people/1024…

| GitHub: github.com/JiangXia-10…

| WeChat public account: 1024 note

This article is about 5165 words, and the expected reading time is 13 minutes

foreword

There are several annotations for processing url request parameters in springboot, they are:

@PathVariable, @RequestHeader, @RequestParam, @MatrixVariable, @RequestBody, let's learn together 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: Whether it is required, the default is true, that is, the request must include this parameter, if 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 is false (optional configuration)

for example:

 @RequestMapping("/testequestparam")
    public String testequestParam(@RequestParam("name") String name){
        return name+",你好啊!";
    }
复制代码

The output is as follows:

picture

Because the required parameter is true by default, it is necessary. If there is no parameter after the request address, an error will be reported:

picture

If you set its value 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+",你好啊!";
    }
复制代码

picture

@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+",你好啊!";
    }
复制代码

picture

2、@PathVariable

@PathVariable is a new feature of spring 3.0, used to receive the value of the 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/李四/band/比亚迪/
    public String testPathVariable(@PathVariable("id") Integer id,
                                   @PathVariable("name") String name,
                                   @PathVariable("band")String band,
                                   @PathVariable Map<String,String> pv){
        return "返回的车是"+name+"的名下id为"+id+"的车,车子的品牌是"+band;
    }
复制代码

The returned results are as follows:

picture

@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;
    }
复制代码

picture

In addition, @PathVariable also has the same attribute required as @RequestParam, and the usage is the same, so it will not be explained here.

3、@RequestHeader

We know that a request will contain some request header information, as follows:

picture

@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;
    }
复制代码

picture

4、@MatrixVariable

The @MatrixVariabl annotation extends the function of the URL request address. Multiple variables can be used when @Matrixvariable annotation is used; (semicolon) separated, this annotation allows developers to perform multi-condition combined queries. 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 attributes are basically the same as RequestParam, but there is an additional pathVar attribute, which indicates the name of the URI path variable where the matrix variable is located, and disambiguates if necessary (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 annotations, and needs to be processed, because SpringBoot disables the function of matrix variables by default, and needs to be processed manually. The processing of the path is parsed through UrlPathHelper, removesemicolonconten (remove the semicolon content) Support 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表示不移除;后面的内容,矩阵变量功能就能生效
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
}
复制代码

picture

5、@RequestBody

@RequestBody is mainly used to receive the data in the json string passed from the front end to the backend (data in the request body); and the most commonly used request body to pass parameters is undoubtedly the POST request, so when using @RequestBody to receive data , usually submitted by POST. The source code is as follows:

public @interface RequestBody {
  boolean required() default true;
}
复制代码

This annotation has only one required attribute, which is true by default. Use as follows:

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

picture

Summarize

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

If you have any questions or mistakes, welcome to communicate, discuss and learn together!

The source code of this project is at:

github.com/JiangXia-10…

Welcome to download, Star!

related suggestion

Guess you like

Origin blog.csdn.net/qq_41153943/article/details/124908929