Spring Boot参数绑定注解详解及其使用场景

在使用Spring Boot做接口开发的过程当中发现接受参数的注解,有时不能准确理解其含义,故抽空总结一下以备未来参阅。json

首先将经常使用的handler method注解经过他们处理Request的不一样内容部分,分类以下:cookie

1. 处理request uri部分(这里指uri template中variable,不含queryString部分)的注解: @PathVariable;

2. 处理request header部分的注解:@RequestHeader,@CookieValue;

3. 处理request body部分的注解:@RequestParam, @RequestBody;

4. 处理attribute类型是注解:@SessionAttributes, @ModelAttribute;

下面是几个注解的说明:session

1. @RequestParam

  • 经常使用来处理简单类型的绑定,经过Request.getParameter()获取的String可直接转换为简单类型的状况;由于使用request.getParameter()方式获取参数,因此能够处理get和post方式中queryString的值,也能够处理post方式中post方式中body data的值,此时的请求类型为application/x-www-form-urlencoded,若是类型为application/json,只能用@RequestBody处理;app

  • 该注解有两个属性:value、required;value用来指定要传入值的id名称,required不写默认是true;框架

@RequestMapping("/login")
public String login(@RequestParam(value="username") String username, @RequestParam(value="password") String password){

	return username+password;
}

2. @RequestBody

  • 该注解经常使用来处理Content-Type:通常是application/json,application/xml;经过使用HandlerAdapter配置的HttpMessageConverters来解析post data body,而后绑定到相应的bean上的。支持post、put方式。
@RequestMapping(value="/something", method=RequestMethod.PUT)
public void handle(@RequestBody String body){
	System.out.println(body);
}

3. @PathVariable

  • 经过@PathVariable能够将URL中占位符参数绑定到控制器处理方法的入参中:URL中的{xxx}占位符能够经过@PathVariable("xxx")绑定到操做方法的入参中。促使SpringMVC支持Rest风格。
@RequestMapping("/get/{id}")
public void getSomethingById(@PathVariable String id) {
	// implementation omitted
}

4. @RequestHeader,@CookieValue;

(1) @RequestHeader

@RequestHeader注解,能够把Request请求header部分的值绑定到方法的参数上。jsp

@RequestMapping("/setHeader")
public void setHeaderInfo(@RequestHeader("Accept-Encoding") String encoding, @RequestHeader("Keep-Alive") long keepAlive) {

}
  • 上述代码将request header部分的Accept-Encoding的值,绑定到参数encoding上了,Keep-Alive header的值绑定到参数keepAlive上。

为了固定参数统一处理,固然也支持在header中传入参数,如token信息,此时的写法以下:post

@RequestMapping("/setHeader")
public void setHeaderInfo(@RequestHeader String token) {
	//...
}

(2)@CookieValue

@CookieValue能够把Request header中关于Cookie的值绑定到方法的参数上。ui

@RequestMapping("/setHeader")
public void setHeaderInfo(@CookieValue("JSESSIONID") String cookie) {
	// ...
}

上述代码将JSESSIONID的值绑定到参数cookie上。url

5. @SessionAttributes, @ModelAttribute

(1)SessionAttributes

该注解用来绑定HttpSession中的attribute对象的值,便于在方法中的参数里使用。默认状况下SpringMVC将模型中的数据存储到request域中。当一个请求结束后,数据就失效了。若是要夸页面使用,那么须要使用到session。而@SessionAttribute注解就可使得模型中的数据存储一份到session域中。.net

@Controller
@RequestMapping("/editPet.do")
@SessionAttributes("attr1","attr2")
public class TestSessionAttributes {

	@RequestMapping(values="/index1")
	public ModelAndView index(){
		ModelAndView mav = new ModelAndView("index.jsp");
		mav.addObject("attr1","attr1Value");
		mav.addObject("attr2","attr2Value");
		return mav;
	}
	
	
	@RequestMapping(values="/index2")
	public ModelAndView index2(@ModelAttribute("attr1") String attr1, @ModelAttribute("attr2") String attr2) {
		ModelAndView mav = new ModelAndView("success.jsp");
		return mav;
	}
}

index方法返回一个ModelAndView其中包括视图index.jsp和两个键值放在model中,在没有加入@SessionAttributes注解的时候,放入model当中的键值是request级别的。

如今由于在Controller上面标记了@SessionAttributes(value={"attr1", "attr2"})那么model中的attr1, attr2会同步到session中,这样访问index而后再去访问index2的时候也会获取这两个属性的值。

当须要清除session中的值的时候,咱们只须要在controller的方法中传入一个SessionStatus的类型对象,经过调用setComplete方法就能够清除了。

@RequestMapping(params="method=index3")
public ModelAndView index4(SessionStatus status) {
	ModelAndView mav = new ModelAndView("success.jsp");
	status.setComplete();
	return mav;
}

另外,@SessionAttribute注解只能在类上使用,不能在方法上使用。

(2)ModelAttribute

该注解有两个用法,一个是用于方法上,一个是用于参数上;

用于方法上时:一般用来在处理@RequestMapping以前,为请求绑定须要从后台查询的model;

用于参数上时:用来经过名称对应,把相应名称的值绑定到注解的参数bean上;

要绑定的值来源于:

A) @SessionAttributes启用的attribute对象上;

B) @ModelAttribute用于方法上时指定的model对象;

C) 上述两种状况都没有时,new一个须要绑定的bean对象,而后把request中按名称对应的方式把值绑定到bean中。

  • @ModelAttribute用在参数上:
@RequestMapping("/hello")
public ModelAndView hello(@ModelAttribute Account account) {
	acount.setAge(12);
	account.setName("456");
	return new ModelAndView("hello");
}

注解在方法参数上的@ModelAttribute说明了该方法的值将由model中取得。若是model中找不到,那么该参数会先被实例化,而后被添加到model中。在model中存在之后,请求中全部名称匹配的参数都会填充到该参数中。这在Spring MVC中被称为数据绑定,一个很是有用的特性,节约了每次都须要手动从表格数据中转换这些字段数据的时间。

  • @ModelAttribute用在方法上:

方法经过返回值的方式默认地将添加一个属性。属性名没有被显式指定的时候,框架将根据属性的类型给予一个默认名称。例如:本例返回一个Account类型的对象,则默认的属性名为"account",你能够经过设置@ModelAttribute注解的值来改变默认值。

@ModelAttribute
public Account addAccount(@RequestParam(value = "name", defaultValue = "test") String name) {
	Account ac = new Account();
	ac.setName(name);
	ac.setAge(12);
	return ac;
}

参考文章:

https://blog.csdn.net/ztchun/article/details/84073120

相关文章
相关标签/搜索