当前位置: 移动技术网 > IT编程>开发语言>Java > SpringMVC框架详细教程(九)_使用 @RequestParam 将请求参数绑定至方法参数

SpringMVC框架详细教程(九)_使用 @RequestParam 将请求参数绑定至方法参数

2020年04月18日  | 移动技术网IT编程  | 我要评论

使用 @requestparam 将请求参数绑定至方法参数

你可以使用 @requestparam 注解将请求参数绑定到你控制器的方法参数上。

下面这段代码展示了它的用法:

package com.pudding.controller;

import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestparam;

@controller
public class editpetform {

	@getmapping("/pets")
	public string setupform(@requestparam int petid) {
		system.out.println(petid);
		return "petform";
	}

}

若参数使用了该注解,则该参数默认是必须提供的,但你也可以把该参数标注为非必须的:只需要将 @requestparam 注解的 required 属性设置为 false 即可:

package com.pudding.controller;

import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestparam;

@controller
public class editpetform {

	@getmapping("/pets")
	public string setupform(@requestparam(value = "petid", required = false) integer petid) {
		system.out.println(petid);
		return "petform";
	}

}

注意:这里使用的 required = false 是将请求的参数设置为 null ,所以方法里的参数需要为引用类型(integer),如果使用的是基本类型(int)会出现以下错误:

java.lang.illegalstateexception: optional int parameter 'petid' is present but cannot be translated into a null value due to being declared as a primitive type. consider declaring it as object wrapper for the corresponding primitive type.

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网