SpringMVC中@RequestMapping处理请求参数的@RequestParam注解

来源:互联网 发布:最红网络伤感歌曲大全 编辑:程序博客网 时间:2024/05/18 03:14

首先在页面添加一个带有参数的请求,分别是username和age

<a href="springmvc/testRequestParam?username=yoni&age=20">Test RequestParam</a>

然后在类中添加方法

@RequestMapping("/testRequestParam")public String testRequestParam(@RequestParam(value="username") String username,@RequestParam(value="age") int age ){System.out.println("Test RequestParam UserName:" + username + ",age:"+ age);return SUCCESS;}

运行页面,后台会显示

Test RequestParam UserName:yoni,age:20

如果将请求修改为

<a href="springmvc/testRequestParam?username=yoni">Test RequestParam</a>

会出现报错,

HTTP Status [400] – [Bad Request]

Type Status Report

Message Required Integer parameter 'age' is not present

Description The server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).


因为类中的age定义的是int类型,不能为空值。

可以在注解中添加required = false,并将age定义为Integer,问题解决。

@RequestMapping("/testRequestParam")public String testRequestParam(@RequestParam(value="username") String username,@RequestParam(value="age",required = false) Integer age ){System.out.println("Test RequestParam UserName:" + username + ",age:"+ age);return SUCCESS;}

但如果非要设置成int,那需要给age参数附一个默认值,修改代码如下

@RequestMapping("/testRequestParam")public String testRequestParam(@RequestParam(value="username") String username,@RequestParam(value="age",required = false,defaultValue="0") Integer age ){System.out.println("Test RequestParam UserName:" + username + ",age:"+ age);return SUCCESS;}

@RequestParam注解中,value对应的是请求参数中的参数名,requirde是设置该参数是否必须存在,defaultValue是设置该参数的默认值。

阅读全文
0 0
原创粉丝点击