Spring MVC和X-HTTP-Method-Override参数

Ido*_*ohn 5 java spring http spring-mvc

我正在使用Spring MVC,我有一个更新用户配置文件的功能:

@RequestMapping(value = "/{userName}" + EndPoints.USER_PROFILE,
    method = RequestMethod.PUT)
public @ResponseBody ResponseEntity<?> updateUserProfile(
    @PathVariable String userName, @RequestBody UserProfileDto userProfileDto) {
    // Process update user's profile
} 
Run Code Online (Sandbox Code Playgroud)

我已经开始使用JMeter了,由于某种原因,他们遇到了与正文发送PUT请求的问题(在请求正文中或使用请求参数hack).

我知道在Jersey中你可以添加一个过滤器来处理X-HTTP-Method-Override请求参数,这样你就可以发送一个POST请求并使用header参数覆盖它.

有没有办法在Spring MVC中做到这一点?

谢谢!

cod*_*ark 10

Spring MVC有HiddenHttpMethodFilter,它允许你包含一个请求参数(_method)来覆盖http方法.您只需要在web.xml中将过滤器添加到过滤器链中.

我不知道使用X-HTTP-Method-Override标头的开箱即用解决方案,但您可以创建一个类似于您HiddenHttpMethodFilter自己的过滤器,它使用标头来更改值而不是请求参数.


Utk*_*mir 6

您可以使用此类作为过滤器:

public class HttpMethodOverrideHeaderFilter extends OncePerRequestFilter {
  private static final String X_HTTP_METHOD_OVERRIDE_HEADER = "X-HTTP-Method-Override";

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
      throws ServletException, IOException {
    String headerValue = request.getHeader(X_HTTP_METHOD_OVERRIDE_HEADER);
    if (RequestMethod.POST.name().equals(request.getMethod()) && StringUtils.hasLength(headerValue)) {
      String method = headerValue.toUpperCase(Locale.ENGLISH);
      HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, method);
      filterChain.doFilter(wrapper, response);
    }
    else {
      filterChain.doFilter(request, response);
    }
  }

  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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

来源:http : //blogs.isostech.com/web-application-development/put-delete-requests-yui3-spring-mvc/