@Restcontroller
它继承自@Controller注解。4.0之前的版本,Spring MVC的组件都使用@Controller来标识当前类是一个控制器servlet。
使用这个特性,我们可以开发REST服务的时候不需要使用@Controller而专门的@RestController。
当你实现一个RESTful web services的时候,response将一直通过response body发送。
@controller
通过@controller标注即可将class定义为一个controller类。
Controller控制器是通过服务接口定义的提供访问应用程序的一种行为,它解释用户的输入,将其转换成一个模型然后将试图呈献给用户。Spring MVC 使用 @Controller 定义控制器,它还允许自动检测定义在类路径下的组件并自动注册。如想自动检测生效,需在XML头文件下引入 spring-context:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?
xml
version
=
"1.0"
encoding
=
"UTF-8"
?><
beans
xmlns
=
"http://www.springframework.org/schema/beans"
xmlns:xsi
=
"http://www.w3.org/2001/XMLSchema-instance"
xmlns:p
=
"http://www.springframework.org/schema/p"
xmlns:context
=
"http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<
context:component-scan
base-package
=
"org.springframework.samples.petclinic.web"
/>
<!-- ... -->
</
beans
>
|
@RequestMapping
我们可以 @RequestMapping 注解将类似 “/favsoft”这样的URL映射到整个类或特定的处理方法上。一般来说,类级别的注解映射特定的请求路径到表单控制器上,而方法级别的注解只是映射为一个特定的HTTP方法请求(“GET”,“POST”等)或HTTP请求参数。
既可以作用在类级别,也可以作用在方法级别。当它定义在类级别时,标明该控制器处理所有的请求都被映射到 /favsoft 路径下。@RequestMapping中可以使用 method 属性标记其所接受的方法类型,如果不指定方法类型的话,可以使用 HTTP GET/POST 方法请求数据,但是一旦指定方法类型,就只能使用该类型获取数据。
可以使用 @Validated与BindingResult联合验证输入的参数,在验证通过和失败的情况下,分别返回不同的视图。
支持使用URI模板访问URL。URI模板像是URL模样的字符串,由一个或多个变量名字组成,当这些变量有值的时候,它就变成了URI。
value | 表示需要匹配的url的格式。 |
method | 表示所需处理请求的http 协议(如get,post,put,delete等),可选值为RequestMethod这个enum的值。 |
params | 格式为”paramname=paramvalue” 或 “paramname!=paramvalue”。 表示参数必须等于某值,或者不等于才进入此映射方法。不填写的时候表明不限制 |
headers | 用来限定对应的reqeust请求的headers中必须包括的内容,例如headers={"Connection=keep-alive"}, 表示请求头中的connection的值必须为keep-alive。 |
@RequestParam
将请求的参数绑定到方法中的参数上,如下面的代码所示。其实,即使不配置该参数,注解也会默认使用该参数。如果想自定义指定参数的话,如果将@RequestParam的 required 属性设置为false(如@RequestParam(value="id",required=false))。
value | 对应表单name空间的值 |
required | 是否允许为空 |
defaultValue | 默认值 |
@PathVariable
可以使用 @PathVariable 注解方法参数并将其绑定到URI模板变量的值上
获得地址栏中传的参数 例如:
- @RequestMapping(value="/{groupId}.do")
- public void detail(@PathVariable long groupId){
- groupRepository.selectOne(groupId);
- }
public String findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) { Owner owner = ownerService.findOwner(ownerId); Pet pet = owner.getPet(petId); model.addAttribute("pet", pet);
return "displayPet"; }
@RequestBody
在参数之前加入@RequestBody注解。用来将指定的客户端发送过来的请求参数的数据格式转换成java实体
- @RequestMapping(value = "/xxxxx.do")
- public void create(@RequestBody() String host){
- System.out.println("-----------" + host);
- }
@RequestHeader
在参数之前加入@RequestHeader注解。用来将指定的请求头信息影射为方法的参数。
- @RequestMapping(value = "/xxxxx.do")
- public void create(@RequestHeader() MultiValueMap<String, String> host){
- System.out.println("-----------" + host);
- }
@ResponseBody
如果这个方法定义了@ResponseBody注解。那么会把返回值转换成这个数据格式,输出给客户端
@ResponseBody与@RequestBody类似,它的作用是将返回类型直接输入到HTTP response body中。@ResponseBody在输出JSON格式的数据时,会经常用到
- @RequestMapping(value = "/xxx.do")
- @ResponseBody
- public MultiValueMap<String, String> create(@RequestHeader() MultiValueMap<String, String> hosts) throws Exception {
- return hosts;
- }
返回一个指定的http response状态码。
- @ResponseStatus(reason="no reason",value=HttpStatus.BAD_REQUEST)
- @RequestMapping("/responsestatus")
- public void responseStatusTest(){
- }
@SessionAttributes
写在类级别的注解,定义一个session attributes,属性名字为SessionAttributes指定。可以指定多个(数组),也同时可以指定类型。
- @Controller
- @SessionAttributes( { "user" })
- @RequestMapping("/test")
- public class ControllerTest {
- @RequestMapping("/session")
- @ResponseBody
- public String sessionIn(@ModelAttribute("user") User user) {
- return "index";
- }
- }
@CookieValue
- @RequestMapping("/cookie")
- @ResponseBody
- public String cookie(@CookieValue("JSESSIONID") String sessionId) {
- return sessionId;
- }
@InitBinder
在controller中注册一个customer protperty editor以解析request中的参数并通过date bind机制与handler method中的参数做绑定。
- @InitBinder
- public void initBinder(WebDataBinder binder) {
- SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
- dateFormat.setLenient(false);
- binder.registerCustomEditor(Date.class, new CustomDateEditor(
- dateFormat, false));
- }
- @RequestMapping("/databind1")
- public ModelAndView databind1(Date date) {
- …
- }
访问url http://localhost:8080/springmvc/databind1.action?date=2000-01-02
通过initbinder中注册的customeDateEditor类型,自动将2000-01-02转换为日期类型
@ExceptionHandler
- @RequestMapping("/exception")
- public void ExceptionTest() throws Exception{
- throw new Exception("i don't know");
- }
- @ExceptionHandler
- public String handleException(Exception e,HttpServletRequest request){
- System.out.println(e.getMessage());
- return "helloworld";
- }
public ResponseEntity<String> handle(HttpEntity<byte[]> requestEntity) throws UnsupportedEncodingException { String requestHeader = requestEntity.getHeaders().getFirst("MyRequestHeader"));
byte[] requestBody = requestEntity.getBody();
// do something with request header and body HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("MyResponseHeader", "MyValue");
return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.CREATED); }
@ModelAttribute public Account addAccount(@RequestParam String number) { return accountManager.findAccount(number); } @ModelAttribute public void populateModel(@RequestParam String number, Model model) { model.addAttribute(accountManager.findAccount(number)); // add more ... }