Springboot处理请求参数的注解

前言

在springboot中有几种处理url请求参数的注解,它们分别是:

@PathVariable、@RequestHeader、@RequestParam、@MatrixVariable、@RequestBody,今天一起来学习下。

 

正文

1、@RequestParam

@RequestParam 可以用于将指定的请求参数赋值给方法中的形参。源码如下:

1
2
3
4
5
6
7
8
public @interface RequestParam {
  @AliasFor("name")
  String value() default "";
  @AliasFor("value")
  String name() default "";
  boolean required() default true;
  String defaultValue() default ValueConstants.DEFAULT_NONE;
}

 

可以发现它有三个属性:

  •  value:请求参数名(必须配置)

  • required:是否必需,默认为 true,即 请求中必须包含该参数,如果没有包含,将会抛出异常(可选配置)

  • defaultValue:默认值,如果设置了该值,required 将自动设为 false,无论你是否配置了required,配置了什么值,都是 false(可选配置)

比如:

1
2
3
4
@RequestMapping("/testequestparam")
public String testequestParam(@RequestParam("name") String name){
    return name+",你好啊!";
}

 输出结果如下:

 

 

 

因为required参数默认是true,所以是必须的,如果请求地址后面不带参数则会报错:

 

 

 

如果将其值设为false,则请求成功,但是参数值为null:

1
2
3
4
@RequestMapping("/testequestparam1")
public String testequestParam1(@RequestParam(value="name",required = false) String name){
    return name+",你好啊!";
}

 

 

 

@RequestParam还可以在参数为空的情况下,为我们设置一个参数的默认值:

1
2
3
4
@RequestMapping("/testequestparam2")
public String testequestParam2(@RequestParam(defaultValue = "defaultValue") String name){
    return name+",你好啊!";
}

 

 

 

2、@PathVariable

@PathVariable是spring3.0的一个新功能,用来接收请求路径中占位符的值,源码如下:

1
2
3
4
5
6
7
public @interface PathVariable {
  @AliasFor("name")
  String value() default "";
  @AliasFor("value")
  String name() default "";
  boolean required() default true;
}

 示例:

1
2
3
4
5
6
7
8
@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;
}

 

返回结果如下:

 

 

@PathVariable支持返回所有的路径变量:

1
2
3
4
5
6
7
8
9
10
11
12
@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;
}

 

 

 

除此之外@PathVariable还有和@RequestParam相同的属性required,用法一样,这里不再说明。

3、@RequestHeader

我们知道一个请求中会包含一些请求头等信息,如下:

 

 

 

@RequestHeader是获取请求头中的数据,通过指定参数 value 的值来获取请求头中指定的参数值。源码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
public @interface RequestHeader {
  
  @AliasFor("name")
  String value() default "";
 
  @AliasFor("value")
  String name() default "";
 
  boolean required() default true;
 
  String defaultValue() default ValueConstants.DEFAULT_NONE;
 
}

 通过源码可以发现其他参数用法和 @RequestParam完全一样。示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@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

@MatrixVariabl注解拓展了URL请求地址的功能。使用@Matrixvariable注解时多个变量可以使用;(分号)分隔,该注解允许开发者进行多条件组合査询。其源码如下:

1
2
3
4
5
6
7
8
9
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;
}

可以发现其属性和RequestParam基本完全一样,但是多了一个pathVar属性,它表示矩阵变量所在的URI路径变量的名称,如有必要消除歧义(例如,在多个路径段中存在同名的矩阵变量)。示例:

1
2
3
4
5
6
7
8
9
10
11
@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;
<br>    }

 它和前面的注解直接使用是不行的,需要进行处理,因为SpringBoot默认是禁用了矩阵变量的功能,需要进行处理手动开启,对于路径的处理是通过UrlPathHelper进行解析,removesemicolonconten(移除分号内容)支持矩阵变量:这里写一个配置类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@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);
    }
}

 

 

 

5、@RequestBody

@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的);而最常用的使用请求体传参的无疑是POST请求了,所以使用@RequestBody接收数据时,一般都用POST方式进行提交。源码如下:

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

 该注解只有一个required属性,默认是true。使用如下:

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

 

总结

以上就是springboot中几个对于请求参数处理的注解,通过这些注解我们能够获取url中的参数然后进行对应的业务开发处理。

 

posted @   IT6889  阅读(790)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示