GET请求方式有以下几种:
@RequestMapping(path = "/{id}", method = RequestMethod.GET) 单一参数
1) public String getUser(@PathVariable int id ) {}
2)@RequestMapping(path = "/{sid}/{name}", method = RequestMethod.GET)
可以同时指定多个提交方法
getUser(@PathVariable("sid") String id,@PathVariable("name") String name)
3)可以简化
@GetMapping = @RequestMapping(method = RequestMethod.GET)
@PostMapping = @RequestMapping(method = RequestMethod.POST)
@PutMapping = @RequestMapping(method = RequestMethod.PUT)
@DeleteMapping = @RequestMapping(method = RequestMethod.DELETE)
4)@RequestParam(value = "name", required = true)
可以设置默认值,比如分页
4)@RequestBody 请求体映射实体类
需要指定http头为 content-type为application/json charset=utf-8
5)@RequestHeader 请求头
@RequestHeader("access_token") String accessToken
6)HttpServletRequest request自动注入获取参数
Student实体类(int id,String name,String pass,Date birthday)其他忽;
Controller代码:
//测试HTTP协议GET请求
@RestController //返回JSON到前端的
public class GetController {
//map对象
Map<String,Object> maps =new HashMap<>();
/**
* 测试restful协议,从路径中获取字段
* @param id
* @param name
* @return
*/
@RequestMapping(path = "/find/{id}/{st_name}",method = RequestMethod.GET)
public Object findStudent(@PathVariable("id") int id,@PathVariable("st_name") String name){
maps.clear(); //清空
maps.put("id",id);
maps.put("name",name);
return maps;
}
/**
* 测试GetMapping
* @param id
* @param name
* @return
* 简化:@RequestMapping(method = {RequestMethod.GET})
*/
@GetMapping("/find1")
public Object find1(int id,String name){
maps.clear(); //清空
maps.put("id",id);
maps.put("name",name);
return maps;
}
/**
* 默认值:是否要有必须的参数
* @param id
* @param name
* @return 如果不传值就会是默认值!
*/
@GetMapping("/find2")
public Object find2(@RequestParam(defaultValue = "0",name = "sid") int id,String name){
maps.clear(); //清空
maps.put("id",id);
maps.put("name",name);
return maps;
}
/**
* 注意:1、注意需要指定http头为 content-type为application/json
* * 2、使用body传输数据
* @param stu
* @return
*/
@RequestMapping("/find3")
public Object find3(@RequestBody Student stu){
maps.clear(); //清空
maps.put("stu",stu);
return maps;
}
/**
* HttpServletRequest 请求获取参数值
* @param request 自动注入获取参数
* @return
*/
@GetMapping("/find4")
public Object find4(HttpServletRequest request){
maps.clear(); //清空
maps.put("id",request.getParameter("id"));
return maps;
}
/**
* 测试获取http头信息
* @return
*/
@GetMapping("/find5")
public Object find5(@RequestHeader("access-token")String accessToken, int id){
maps.clear(); //清空
maps.put("id",id);
maps.put("access-token",accessToken);
return maps;
}
}
依次看效果:
0) 测试restful协议,从路径中获取字段
1)测试GetMapping
如果选择是POST,则发生异常哦!
2)如果不传值就会是默认值!
3)返回整个JSON对象
如果没有传值,可以自己传值哦!
4)HttpServletRequest 请求获取参数值
5)测试获取http头信息