在 jQuery 中这样发送 Ajax 请求:
$.ajax({
url: '/xxx/' + id + '/update',
type: 'POST',
data: {
_method: 'PUT'
},
dataType: 'HTML',
success: function(data) {
...
}
});
在 Spring Controller 这样接收请求:
@RequestMapping(value = "/xxx/{id}/update", method = RequestMethod.PUT)
public String update(HttpServletRequest request, @PathVariable("id") Long xxxId) {
...
}
在 web.xml 中一定要配置:
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<servlet-name>dbproxymanage</servlet-name>
</filter-mapping>
<form method="POST">这里不要变动。
在form内部加上一hidden域
<input type="hidden" name="_method" value="put" />就可以了。
浏览器本身只支持get和post方法,使用_method来告知spring这是一个put请求。
建议你使用spring的taglib,写form会方便很多,还可以绑定model。
配置如下:
- <servlet>
- <servlet-name>dbproxymanage</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/classes/spring/*.xml</param-value>
- </init-param>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>dbproxymanage</servlet-name>
- <url-pattern>*.do</url-pattern>
- </servlet-mapping>
最后附上HiddenHttpMethodFilter源码:
public class HiddenHttpMethodFilter extends OncePerRequestFilte{
/** Default method parameter: <code>_method</code> */
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);
}
}