• 表单提交会带上 _method=PUT
    • 请求过来被 HiddenHttpMethodFilter 拦截
      • 请求是否正常,并且是 POST
      • 获取到 _method 的值。
      • 兼容以下请求;PUT.DELETE.PATCH
      • 原生request(post),包装模式requesWrapper重写了getMethod方法,返回的是传入的值。
      • 过滤器链放行的时候用wrapper。以后的方法调用getMethod是调用requesWrapper的。

    [

    ](https://blog.csdn.net/u011863024/article/details/113667634)

    1. public class HiddenHttpMethodFilter extends OncePerRequestFilter {
    2. private static final List<String> ALLOWED_METHODS =
    3. Collections.unmodifiableList(Arrays.asList(HttpMethod.PUT.name(),
    4. HttpMethod.DELETE.name(), HttpMethod.PATCH.name()));
    5. /** Default method parameter: {@code _method}. */
    6. public static final String DEFAULT_METHOD_PARAM = "_method";
    7. private String methodParam = DEFAULT_METHOD_PARAM;
    8. /**
    9. * Set the parameter name to look for HTTP methods.
    10. * @see #DEFAULT_METHOD_PARAM
    11. */
    12. public void setMethodParam(String methodParam) {
    13. Assert.hasText(methodParam, "'methodParam' must not be empty");
    14. this.methodParam = methodParam;
    15. }
    16. @Override
    17. protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
    18. throws ServletException, IOException {
    19. HttpServletRequest requestToUse = request;
    20. if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
    21. String paramValue = request.getParameter(this.methodParam);
    22. if (StringUtils.hasLength(paramValue)) {
    23. String method = paramValue.toUpperCase(Locale.ENGLISH);
    24. if (ALLOWED_METHODS.contains(method)) {
    25. requestToUse = new HttpMethodRequestWrapper(request, method);
    26. }
    27. }
    28. }
    29. filterChain.doFilter(requestToUse, response);
    30. }
    31. /**
    32. * Simple {@link HttpServletRequest} wrapper that returns the supplied method for
    33. * {@link HttpServletRequest#getMethod()}.
    34. */
    35. private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
    36. private final String method;
    37. public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
    38. super(request);
    39. this.method = method;
    40. }
    41. @Override
    42. public String getMethod() {
    43. return this.method;
    44. }
    45. }
    46. }
    • Rest使用客户端工具。
      • 如PostMan可直接发送put、delete等方式请求。