在form中,method只用GET/POST。如果使用PUT/DELETE呢
在spring 的web应用中使用PUT/DELETE访问方式:代码如下:
<form th:action="@{/app/account/update}" method="post">
<input type="hidden" name="_method" value="PUT" />
<input type="submit" value="submit" />
</form>
将你要的访问方式如下<input type="hidden" name="_method" value="PUT" />放到form中,并设置form的方式method="post"。
为什么是这样呢?
因为在页面访问要通过一个spring过滤器:HiddenHttpMethodFilter
代码如下:
public class HiddenHttpMethodFilter extends OncePerRequestFilter {
/** Default method parameter: {@code _method} */
public static final String DEFAULT_METHOD_PARAM = "_method";
private String methodParam = DEFAULT_METHOD_PARAM;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
//当method的方式为post并且_method不为空
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);
}
}
//method转换
/**
* Simple {@link HttpServletRequest} wrapper that returns the supplied method for
* {@link HttpServletRequest#getMethod()}.
*/
private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
private final String method;
public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
super(request);
this.method = method;
}
@Override
public String getMethod() {
return this.method;
}
}
}
这样一看就明明白白了。。。
@RequestMapping(value="/update",method=RequestMethod.PUT)
public String update() throws Exception{
System.out.println("test");
return "account/get";
}