@PathVariable 绑定 URL 占位符与 REST 风格请求
这里用到一个标注 @PathVariable,用于绑定 URL 占位符到方法参数。
web.xml 配置
在 web.xml 中配置 HiddenHttpMethodFilter 过滤器。该过滤器用于将 POST 请求转换为 PUT 或 DELETE 请求。默认情况下 Spring MVC 不处理非 GET/POST 的请求,PUT 和 DELETE 本质上都是 POST,通过隐藏字段 _method 来模拟。
<!-- configure the HiddenHttpMethodFilter, convert the post method to put or delete -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>Code language: HTML, XML (xml)
前端表单模拟不同请求方式
<body>
<form action="/SpringMvc/api/user/1" method="post">
<input type="hidden" name="_method" value="PUT">
<input type="submit" value="put">
</form>
<form action="/SpringMvc/api/user/1" method="post">
<input type="submit" value="post">
</form>
<form action="/SpringMvc/api/user/1" method="get">
<input type="submit" value="get">
</form>
<form action="/SpringMvc/api/user/1" method="post">
<input type="hidden" name="_method" value="DELETE">
<input type="submit" value="delete">
</form>
</body>Code language: HTML, XML (xml)
后台控制器
package cn.bamn.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/api")
public class ApiController {
@RequestMapping("show")
public String show(){
return "show";
}
@RequestMapping(value="/user/{id}",method=RequestMethod.GET)
public String get(@PathVariable("id") Integer id){
System.out.println("GET:"+id);
return "/index";
}
@RequestMapping(value="/user/{id}",method=RequestMethod.POST)
public String post(@PathVariable("id") Integer id){
System.out.println("POST:"+id);
return "/index";
}
@RequestMapping(value="/user/{id}",method=RequestMethod.PUT)
public String put(@PathVariable("id") Integer id){
System.out.println("PUT:"+id);
return "/index";
}
@RequestMapping(value="/user/{id}",method=RequestMethod.DELETE)
public String delete(@PathVariable("id") Integer id){
System.out.println("DELETE:"+id);
return "/index";
}
}Code language: JavaScript (javascript)
Previous: 使用 @ExceptionHandler 进行异常处理
Next: 拦截器(Interceptor)