@InitBinder
@InitBinder,这个注解相当于输入输出参数的一个转换,把下面的方法放在spring的bean中就可以生效了,下面的例子是把前端传递的时间戳转换为date,之后响应的时候吧date转换为时间戳。
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
public void setAsText(String value) {
setValue(new Date(Long.valueOf(value)));
}
public String getAsText() {
return String.valueOf(((Date) getValue()).getTime());
}
});
}
-
@RestController
1. 概述
@RestController=@Controller + @ResponseBody。
1.1 @Controller
在一个类上加上这个注解,表示这个类是一个控制器。
1.2 @ResponseBody
在请求方法上加上这个注解,控制器就会将请求响应的数据以指定的格式写入到Response的body中去。
1.3 所以说@RestController就是注册一个控制器,并且将响应的数据以指定的格式写入到Response的body中。
2. 附加
2.1 @RestController注解可以使用在类或者方法上。
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(){
return "hello";
}
}
上面代码部分等同于下面:
@Controller
@ResponseBody
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(){
return "hello";
}
}
@RequestMapping
@RequestMapping此注解即可以作用在控制器的某个方法上,也可以作用在此控制器类上。
当控制器在类级别上添加@RequestMapping注解时,这个注解会应用到控制器的所有处理器方法上。处理器方法上的@RequestMapping注解会对类级别上的@RequestMapping的声明进行补充。
- @RequestMapping可以指定GET、POST请求方式
- @GetMapping等价于@RequestMapping的GET请求方式
例子一:@RequestMapping仅作用在处理器方法上
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(){
return "hello";
}
}
以上代码sayHello所响应的url=localhost:8080/hello。
例子二:@RequestMapping仅作用在类级别上
/**
* Created by wuranghao on 2017/4/7.
*/
@Controller
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(method= RequestMethod.GET)
public String sayHello(){
return "hello";
}
}
以上代码sayHello所响应的url=localhost:8080/hello,效果与例子一一样,没有改变任何功能。
例子三:@RequestMapping作用在类级别和处理器方法上
/**
* Created by wuranghao on 2017/4/7.
*/
@RestController
@RequestMapping("/hello")
public class HelloController {
@RequestMapping(value="/sayHello",method= RequestMethod.GET)
public String sayHello(){
return "hello";
}
@RequestMapping(value="/sayHi",method= RequestMethod.GET)
public String sayHi(){
return "hi";
}
}
这样,以上代码中的sayHello所响应的url=localhost:8080/hello/sayHello。
sayHi所响应的url=localhost:8080/hello/sayHi。
从这两个方法所响应的url可以回过头来看这两句话:当控制器在类级别上添加@RequestMapping注解时,这个注解会应用到控制器的所有处理器方法上。处理器方法上的@RequestMapping注解会对类级别上的@RequestMapping的声明进行补充。
最后说一点的是@RequestMapping中的method参数有很多中选择,一般使用get/post.
其中,各注解的作用为:
@PathVaribale 获取url中的数据
@RequestParam 获取请求参数的值
@GetMapping 组合注解
1.@RequestBody(POST专用):用的最多的注解,该注解与@RequestParam作用类似,区别在于将①传来的多个参数用Map或Entity统一接收,而不用对每个参数分别写注解;②application/json传来的Json字符串的处理;
2.@RequestHeader:获取Header信息;
3.@CookieValue:获取Cookie值。
参考: RestController注解学习_一品_人生的博客-CSDN博客_restcontroller注解
SpringBoot 中常用注解@Controller/@RestController/@RequestMapping介绍_HelloWorld_EE-DevPress官方社区