一、请求映射信息配置
Spring MCV使用org.springframework.web.bind.annotation包中的以下几个Annotation配置请求映射信息:
- 通用请求——@RequestMapping
- 对应接口:org.springframework.web.bind.annotation.RequestMapping
- 应用位置:类和方法
- Get请求——@GetMapping
- 对应接口:org.springframework.web.bind.annotation.GetMapping
- 应用位置:方法
- Post请求——@PostMapping
- 对应接口:org.springframework.web.bind.annotation.PostMapping
- 应用位置:方法
- Delete请求——@DeleteMapping
- 对应接口:org.springframework.web.bind.annotation.DeleteMapping
- 应用位置:方法
- Patch请求——@PatchMapping
- 对应接口:org.springframework.web.bind.annotation.PatchMapping
- 应用位置:方法
- Put请求——@PutMapping
- 对应接口:org.springframework.web.bind.annotation.PutMapping
- 应用位置:方法
二、参数接收
第一类:有注解
- @PathVariable
- 对应接口:org.springframework.web.bind.annotation.PathVariable
- 应用场景:
从URL路径中获取参数,例如:
http://example.com/demo/11253
@RepuestMapping(value="/demo/{id}")
public void demo(@PathVariable(name = "id") String id) {
String address = orderMapper.getAddressById(id);
...
}
- @RequestParam
- 对应接口:org.springframework.web.bind.annotation.RequestParam
- 应用场景:
从Get请求中获取参数,并且方法的参数名可以与请求中的参数名不一样,例如:
http://example.com/demo?data=11253
@GetMapping(value="/demo")
public void demo(@RequestParam(name = "data") String id) {
String address = orderMapper.getAddressById(id);
...
}
- @RequestBody
- 对应接口:org.springframework.web.bind.annotation.RequestBody
- 应用场景:
从Post请求中获取参数,例如:
http://example.com/demo
…
{“name”:“Alice”, “tel”:13212348765, “sex”:“Female”}
@RepuestMapping(value="/add")
public void add(@RequestBody User user) {
long id = userMapper.insert(user)
...
}
- @ModelAttribute注解
- 对应接口:org.springframework.web.bind.annotation.ModelAttribute
- 应用场景:
http://example.com/demo
…
{“name”:“Alice”, “tel”:13212348765, “sex”:“Female”}
@PostMapping(value="/add")
@ResponseBody
public void add(@ModelAttribute User user) {
long id = userMapper.insert(user)
...
}
第二类:无注解
当方法参数无注解时,不可直接从URL路径中获取前端传入的参数。同时,方法参数名(或参数字段名)必须与前端传入的参数名完全一致。
- 应用示例:GET请求
http://example.com/demo?name=Alice&sex=Female
public void demo(String name, String sex) {
String address = orderMapper.selectByCondition(name, sex);
...
}
- 应用示例:POST请求
http://example.com/demo
…
{“name”:“Alice”, “tel”:13212348765, “sex”:“Female”}
@RepuestMapping(value="/add")
public void add(User user) {
long id = userMapper.insert(user)
...
}
第三类:HttpServletRequest接收请求参数
Controller还可以使用HttpServletRequest来接收参数,接收的参数均为String类型。
- 应用示例:
@RequestMapping(value="demo")
public String request(HttpServletRequest request, HttpServletResponse response) {
String name = request.getParameter("name");
String tele = request.getParameter("tel");
return name + ": " + tele;
}