目录
@PathVaribale & @RequestParam & @RequestBody
@Controller&@RestController
项目前后台交互的话 无非两种方式
一种普通整体页面提交,比如form提交;
一种局部刷新,或者叫做异步刷新,ajax提交;
@Controller | 处理http请求, 就是整体页面刷新提交的处理注解 |
---|---|
@RestController | Spring4之后新加的注解,原来返回json需要@ResponseBody配合@Controller |
@RequestMapping | 配置url映射 |
@RequestMapping
RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
RequestMapping注解有六个属性
-
value : 指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);
-
method : 指定请求的method类型, GET、POST、PUT、DELETE等;
-
consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
-
produces : 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
-
params : 指定request中必须包含某些参数值是,才让该方法处理。
-
headers : 指定request中必须包含某些指定的header值,才能让该方法处理请求。
value属性
-
A) 可以指定为普通的具体值;
-
B) 可以指定为含有某变量的一类值(URI Template Patterns with Path Variables);
-
C) 可以指定为含正则表达式的一类值( URI Template Patterns with Regular Expressions);
params、headers 示例
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
}
@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
}
仅处理请求中包含了名为“myParam”,值为“myValue”的请求;
仅处理request的header中包含了指定“Refer”请求头和对应值为“http://www.ifeng.com/”的请求;
@PathVaribale & @RequestParam & @RequestBody
@PathVaribale 获取url中的数据
@RequestParam 获取请求参数的值
@RequestBody 获取POST请求消息体的值
示例
/* 对应 http://127.0.0.1:7091/sayHi/tom */
@RequestMapping("/sayHi/{name}")
public String sayHi(@PathVariable("name")String name ){
return "hi!"+ name;
}
/*对应 http://127.0.0.1:7091/sayHello?name=tom */
@RequestMapping("/sayHello")
public String sayHello(@RequestParam String name){
return "你好!"+name;
}
/* 对应POST http://127.0.0.1:7091/sayGood 消息体为tom */
public String sayGood(@RequestBody(required = false) String name){
return "find!"+name;
}
required属性
-
当required=true,判断数据是否为空,假如数为空时,报错。
-
当required=false,为不判断数据是否为空。