最近在用 Spring Data Rest 写WebApi 遇到Put请求后报415 Mieda Type 的错误,GG了下 找到个解决办法,下面是针对Put请求的过滤。
1 public class HttpPutRestfulContentFilter extends OncePerRequestFilter { private Charset charset = Charset.forName("UTF-8");
private final String method="PUT"; @Override
protected void doFilterInternal(final HttpServletRequest request, HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException { if (this.method.equals(request.getMethod())) {
HttpInputMessage inputMessage = new ServletServerHttpRequest(request) {
@Override
public InputStream getBody() throws IOException {
return request.getInputStream();
}
}; HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, this.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;
}
}
}
需要在web.xml中添加这个自定义过滤
<!--解决使用PUT请求接收不到参数的问题 -->
<filter>
<filter-name>HttpMethodFilter</filter-name>
<filter-class>org.tccsdk.core.code.filter.HttpPutRestfulContentFilter</filter-class>
</filter> <filter-mapping>
<filter-name>HttpMethodFilter</filter-name>
<servlet-name>api</servlet-name>
</filter-mapping> <!-- Spring child -->
<servlet>
<servlet-name>api</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>api</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>