Springboot 2.x 请求参数之 @RequestParam 使用

1、@RequestParam 注解的作用是可以将请求参数绑定到控制器的处理方法的形参上,我们可以通过下面测试案例得出该注解具体的作用

2、@RequestParam 注解源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParam {
    // name 和 value 互为别名,无论使用 name 还是用 value 赋值都是一样的效果
    @AliasFor("name")
    String value() default "";
    @AliasFor("value")
    String name() default "";
    // required 的默然值是 true,当请求参数与 value 对应的值不匹配时就会报错,如果将
    // required 的值设置为 false 时,即便请求参数中不存在于 value 对应的值,它也不会报错
    boolean required() default true;
    // 如果请求参数不存在时,可以通过该属性设置默认的值
    String defaultValue() default "\n\t\t\n\t\t\n\ue000\ue001\ue002\n\t\t\t\t\n";
}

3、浏览器发起请求

http://localhost:8080/SpringMVC/testRequestParam.jsp

4、testRequestParam.jsp 页面

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>测试@RequestParam!!!</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/testRequestParam/1001" method="POST">
    username: <input type="text" name="username"/><br>
    password: <input type="password" name="password"/><br>
    <input type="submit" value="提交">
</form>
</body>
</html>

5、浏览器页面

6、控制器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Controller
public class SpringmvcDemo {
 
    @RequestMapping(value = "/testRequestParam/{userId}", method = RequestMethod.POST)
    public String testSpringMVC01(
            // 如果请求参数中存在 user,那么它会将 user 携带的值赋值给形参 name,如果不存在,在设置 required=false 的情况下,它会使用默认值
            @RequestParam(value="user",required = false,defaultValue = "xiao mao mao!!!")String name,
            // 如果请求参数中存在 password,那么它会将 password 携带的值赋值给形参的 password
            @RequestParam(value = "password")Integer password,
            // 将路径上的 id 值 (1001) 赋值给形参的 id
            @PathVariable("userId") Integer id) {
 
        System.out.println(name);
        System.out.println(password);
        System.out.println(id);
        return "test";
    }
}

7、测试结果

1
2
3
4
// 由于请求参数中没有 user,所以使用了默认值 xiao mao mao!!!
xiao mao mao!!!
12345678
1001

 

posted @   变体精灵  阅读(758)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示