文章目录
一、控制器
1、@RestController
- =
@Controller
+控制器所有方法@ResponseBody
二、映射请求
1、@RequestMapping
- 可在类上、方法上添加
- 属性
//映射的请求路径 String[] value() default {}; //请求方法 RequestMethod[] method() default {};
- 如:
@RequestMapping(value="list",method={RequestMethod.GET})
2、@GetMapping、@PostMapping、@DeleteMapping
- 只能在方法上添加
- 等效于
@RequestMapping(method=RequestMethod.GET)
…
三、响应
1、@ResponseBody
Controller
中的返回值String
默认是转发的视图名或重定向,加上这个注解后,方法的返回值写入ResponseBody
中,返回请求的页面中- 局部刷新数据ajax异步请求、下载文件常用
四、接收请求参数
1、@RequestParam
- 原理是
request.getParameter()
- 可以接收get、post请求的参数,但是只能接收请求的
Content-Type:application/x-www-form-urlencoded
,不能接收RequestBody
中的参数 - 属性
- value:映射请求参数名
- name:=value
- required:是否必须提供该参数,默认值为true,当=true时,该参数就是必须提供的,若没有则
HTTP Status 400 - Required String parameter 'uname' is not present
- defaultValue:默认值,该属性当required=false时才有效
//请求参数中没有username时,则username=配置的defaultValue=Jack @GetMapping("list") public void list (@RequestParam(required=false,defaultValue="Jack") String username){ }
2、@PathVariable
- 将请求URL中的模板变量映射到功能处理方法参数上,即取出url的变量作为方法的参数值
- 参数、数据少的时候用
- 属性
//= name String value() default ""; //= value String name() default ""; //是否必须提供该参数 boolean required() default true;
- 举例
//http://localhost:8080/86 //id=86 @GetMapping("{id}") public void get(@PathVariable Integer id){ } //方法参数名称和需要绑定的url中变量名称不一致时 @GetMapping("{name}") public void get(@PathVariable("name") String username){ } //数组、集合 //let ids=[1,2] //'localhost:8080/'+ids @DeleteMapping("{ids}") public void remove(@PathVariable List<Long> ids){ } //绑定多个url参数 @GetMapping("{id}/{name}") public void get(@PathVariable Integer id,@PathVariable String name){ }
3、@PathParam
- 从地址栏取对应键的值,没有对应属性时会是一个null值,不会报错
- 举例
//http://localhost:8080/list?age=18 @GetMapping("list") public void list(@PathParam("age") String age){ }
4、@RequestBody
- 可以处理
Content-Type:application/x-www-form-urlcoded、application/json
application/xml - 只能接收Requestbody中参数,用于post、put,不能用于get、delete这种使用URL传参的请求方法
- 只能接受一个参数,一般对象接收
- 举例
@PostMapping public void add(@RequestBody User user){ }