Spring注解系列二

@RequestMapping

用来表示请求地址映射的注解。可以作用在类或者方法上。作用与类上,表示所有响应请求的方法都是以该地址作为父路径。@RequestMapping有六个属性:

  1. value:指定请求的实际地址,指定的地址可以是URI Template模式
  2. method:指定请求的method类型,GET,POST,PUT,DELETE等。
  3. consumers: 指定处理请求的提交内容类型(Content-Type),如:application/json,text/html;
  4. produces:指定返回的内容类型,仅当request请求头中的Accept类型中包含该指定类型才返回。
  5. params: 指定request中必须包含某些参数值,才让该方法处理。
  6. headers: 指定request中必须包含某些指定的header值,才让该方法处理请求。

举个例子:

1
2
3
4
5
6
7
8
9
10
11
@Controller
@RequestMapping(value="hello")
public class HelloController {
@RequestMapping(value = "frank", params = {"param1=value1","param2","!param3"},
method = {RequestMethod.GET}, headers = {"host=localhost","Accept"})
public String helloFrank(){
System.out.println("hello frank");
String msg = "hello frank";
return msg;
}
}

上面的例子只有在请求地址为
hello/frank.do?param1=value1&param2=value2 并且请求方式必须为GET,而且必须是从本机发起,因为header属性中规定了host必须为localhost.

@PathVarible

用于将请求URL中的模板变量映射到方法的参数上,即取出uri模版中的变量作为参数.

1
2
3
4
5
6
7
8
9
10

@RequestMapping(value="/query/{userId}/roles/{roleId}",
method = RequestMethod.GET)
public String query(@PathVariable("userId") String userId,
@PathVariable("roleId") String roleId){
System.out.println("userId" + userId);
System.out.println("roleId" + roleId);
String msg = "hello frank";
return msg;
}

@RequestParam

用来处理Get方式发送过来的请求,获取URL中的参数。例如URL地址为?xxx=aaa&yyy=bbb.

总结:虽然@RequestParam@PathVariable都能获取URL中的变量。一个是使用这种方式 http://localhost:8080/query/{userId}/roles/{roleId}
一个使用这种方式 http://localhost:8080?state=ok.这两种URL的使用区别是,当URL指定某一个具体的业务资源时使用@PathVariable方式。
当URL需要对对资源进行过滤时使用@RequestParam方式。
当URL中某个参数确实不存在时可以使用 required参数
@RequestParam(name="id",required=false,defaultValue="0")

@RequestBody

通过该标签可以获得请求中的body数据并通过HttpMessageConverter序列化为对象。
举个例子:
假设前端通过Jquery发送一个POST请求,请求内容是这样的。
{ "firstName" : "Frank", "lastName" : "Huang" }
我们的Controller是这样的。

1
2
3
4
5
@RequestMapping(value="getUserInfo")
@ResponseBody
public Info getUserInfo(@RequestBody User user){
return new Info(user.getFirstName()+user.getLastName());
}
1
2
3
4
5
6
7
8
9
10
public class User{
private String firstName;
private String lastName;
// 省了getter,setter method
}

public class Info{
private String info;
//省了constructor,getter,setter method
}

Spring 将把请求过来的Json串自动转换为User对象(@RequestBody在起作用)。并且在返回的时候会自动转化为Info对象(@ResponseBody在起作用)。

@RequestHeader

可以把Request请求header部分的值绑定到方法的参数上。

1
2
3
4
5
6
Host        localhost:8080  
Accept text/html,application/xhtml+xml,application/xml;q=0.9
Accept-Language fr,en-gb;q=0.7,en;q=0.3
Accept-Encoding gzip,deflate
Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive 300
1
2
3
4
5
6
@GetMapping("/demo")
public void handle(
@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive) {
//...
}

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

@CookieValue

可以把Request Header中关于cookie的值绑定到方法的参数上。
JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84

1
2
3
4
@GetMapping("/demo")
public void handle(@CookieValue("JSESSIONID") String cookie) {
//...
}

即把JSESSIONID的值绑定到参数cookie上。

@ModelAttribute

该注解主要用来关联模型属性。假设我们有个表单,有个对应的模型对象 Person。我们想在Controller中使用该对象,可以这样

1
2
3
public String processForm(@ModelAttribute("person") Person person){
person.getStuff();
}

另一方面该注解用于定义一个模型对象。如果你想定义一个对象,跟模型关联,你可以这样做。

1
2
3
4
@ModelAttribute("person")
public Person getPerson(){
return new Person();
}

这样在View中就可以直接使用这个对象了。

@SessionAttributes

用来在不同请求之间通过session保存属性值。举个例子

1
2
3
4
5
@Controller
@SessionAttributes("pet")
public class EditPetForm {
// ...
}

当第一个请求进来的时候,会把pet属性自动加到HTTP的session中。它会一直保留,直到有方法调用SessionStatus的方法清空该属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Controller
@SessionAttributes("pet")//把Pet保存到Servlet Session中
public class EditPetForm {
// ...
@PostMapping("/pets/{id}")
public String handle(Pet pet, BindingResult errors, SessionStatus status) {
if (errors.hasErrors) {
// ...
}
//从Servlet Session中清空Pet
status.setComplete();
// ...
}
}
}

@SessionAttribute

当你需要访问已经存在的Session中的属性,可以把该注解放在方法参数上。

1
2
3
4
@RequestMapping("/")
public String handle(@SessionAttribute User user) {
// ...
}

@ResponseBody

作用在方法或者Controller上面,通过HttpMessageConverter把返回对象序列化。

1
2
3
4
5
@GetMapping("/accounts/{id}")
@ResponseBody
public Account handle() {
// ...
}

View可以直接使用返回的Account对象。

@Configuration

等同于Spring的XML配置文件;

@EnableAutoConfiguration

自动配置。

@ComponentScan

组件扫描,可自动发现和装配一些bean

@RestController

该注解是@Controller和ResponseBody的合集。Spring4.X以后推荐使用该注解代替@Controller和@ResponseBody。

-------------本文结束-------------
坚持原创技术分享,您的支持将鼓励我继续创作!
0%