1. 程式人生 > >SpringMVC+AJAX處理瀏覽器無法通過put delete方式請求問題

SpringMVC+AJAX處理瀏覽器無法通過put delete方式請求問題

在 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。

配置如下:

  1. <servlet>
  2.     <servlet-name>
    dbproxymanage</servlet-name>
  3.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  4.     <init-param>
  5.         <param-name>contextConfigLocation</param-name>
  6.         <param-value>/WEB-INF/classes/spring/*.xml</param-value>
  7.     </init-param>
  8.     <load-on-startup>1</load-on-startup>
  9. </servlet>
  10. <servlet-mapping>
  11.     <servlet-name>dbproxymanage</servlet-name>
  12.     <url-pattern>*.do</url-pattern>
  13. </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);
    }
}