配置过滤器: HiddenHttpMethodFilter
<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>
配置这个是为了细分POST请求,常用的有POST、PUT、DELETE等。
看下源码:
public class HiddenHttpMethodFilter extends OncePerRequestFilter {
/** Default method parameter: {@code _method} */
public static final String DEFAULT_METHOD_PARAM = "_method";
private String methodParam = DEFAULT_METHOD_PARAM;
/**
* Set the parameter name to look for HTTP methods.
* @see #DEFAULT_METHOD_PARAM
*/
public void setMethodParam(String methodParam) {
Assert.hasText(methodParam, "'methodParam' must not be empty");
this.methodParam = methodParam;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
String paramValue = request.getParameter(this.methodParam);
if ("POST".equals(request.getMethod()) && StringUtils.hasLength(paramValue)) {
String method = paramValue.toUpperCase(Locale.ENGLISH);
HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, method);
filterChain.doFilter(wrapper, response);
}
else {
filterChain.doFilter(request, response);
}
}
可以看到这个过滤器过滤请求,获取name=’_method’携带的数据,一般这个是前台表单提交的细分的POST,比如PUT或者DELETE。过滤器将拦截到的HTTP的method修改为获取的_method值。
- 前台:
<form action="book" method="get">
<button type="submit">查询</button>
</form>
<form action="book" method="post">
<button type="submit">新增</button>
</form>
<form action="book/123" method="post">
<input type="hidden" name="_method" value="PUT">
<button type="submit">修改</button>
</form>
<form action="book/123" method="post">
<input type="hidden" name="_method" value="DELETE">
<button type="submit">删除</button>
</form>
表单里定义一个name=”_method” 的隐藏域,主要是给上面配置的过滤器设置细分的POST请求的method值。
- 后台
@RequestMapping(value = "/book",method = RequestMethod.GET)
public String getBook(){
System.out.println("查询书籍...");
return "success";
}
@RequestMapping(value = "/book",method = RequestMethod.POST)
public String addBook(){
System.out.println("新增书籍...");
return "success";
}
@RequestMapping(value = "/book/{id}",method = RequestMethod.DELETE)
public String deleteBook(@PathVariable("id") String id){
System.out.println("删除书籍,ID为["+id+"]...");
return "success";
}
@RequestMapping(value = "/book/{id}",method = RequestMethod.PUT)
public String updateBook(@PathVariable("id") String id){
System.out.println("修改书籍,ID为["+id+"]...");
return "success";
}
- /book/{id} 中的id是占位符,用于接收前台传过来的数据,使用@PathVariable(“id”)可以将之绑定到方法参数上。
- 可以看到,这一组的增删改查的请求URL是统一的,通过请求的method值进行区分。