请求参数处理
请求映射(Controller)
RequestMapping("/xxx")
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "Hello";
}
}
Rest风格支持(用HTTP请求方式来表示对资源的操作)
- 非rest风格
getUser
,deleteUser
等等
- rest风格
- 只有
/user
- GET表示获取用户
- DELETE表示删除用户
- PUT表示修改用户
- ……
- 只有
@RequestMapping(value = "/user",method = RequestMethod.GET)
- 简化:
GetMapping("/user")
- 表单只能用
get
,post
默认不支持put和delete和petch, 要是表单想rest这两个都用post,然后请求参数里带一个_method = "put"/"delete"
然后配置一下
spring:
mvc:
hiddenmethod:
filter:
enabled: true #开启页面表单的Rest功能
就可以用了 ```java @RequestMapping(value = “/user”,method = RequestMethod.GET) public String getUser(){ return “GET-张三”; }
@RequestMapping(value = “/user”,method = RequestMethod.POST) public String saveUser(){ return “POST-张三”; }
- 非rest风格
@RequestMapping(value = "/user",method = RequestMethod.PUT)
public String putUser(){
return "PUT-张三";
}
@RequestMapping(value = "/user",method = RequestMethod.DELETE)
public String deleteUser(){
return "DELETE-张三";
}
日,你讲了半天就讲了个表单的处理......
<a name="vcyhk"></a>
### 常用参数注解
---
- 获得请求参数 -> `@RequestParam()`
```java
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
// 从请求参数里拿username
return "Hello";
}
获得路径参数 ->
@PathVariable
@RequestMapping("/hello/{id}") public String hello(@PathVariable("id") Integer id){ // 从请求参数里拿username return "Hello"; }
@RequestMapping("/hello/{id}/owner/{username}") public String hello(@PathVariable("id") Integer id, @PathVariable("username") String name){ // 从请求参数里拿username return "Hello"; }
另一种使用方法:
把所有的路径-值的key-value对放在一个Map<String, String>
里,获得所有的参数@RequestMapping("/hello/{id}/owner/{username}") public String hello(@PathVariable Map<String, String> kv){ // 从请求参数里拿username return "Hello"; }
获取请求头 ->
RequestHeader
@RestController public class HelloController { @RequestMapping("/hello/{id}/owner/{username}") public String hello(@PathVariable Map<String, String> kv, @RequestHeader("User-Agent") String useragent){ // 从请求参数里拿username return "Hello"; } }
获得所有的请求头
获得请求参数 ->
@RequestParam
- 单独的
Map<Stirng, String>
获取
cookie
->@CookieValue
@RestController public class HelloController { @RequestMapping("/hello/{id}/owner/{username}") public String hello(@PathVariable Map<String, String> kv, @CookieValue Cookie cookie){ // 从请求参数里拿username return cookie.getName(); } }
获取请求体 ->
@requestBody
@PostMapping("/save") public String postMethod(@RequestBody String content){ return content; }