欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-07-03 23:21:08
...

首先在页面添加一个带有参数的请求,分别是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是设置该参数的默认值。