在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";
}
本文介绍如何在Spring框架中使用PUT和DELETE方法。通过在表单中添加隐藏字段并利用HiddenHttpMethodFilter过滤器,可以实现这些HTTP方法的支持。文章详细解释了过滤器的工作原理及其实现。
3613

被折叠的 条评论
为什么被折叠?



