首页 > 代码库 > Spring Data Rest 支持Put请求
Spring Data Rest 支持Put请求
最近在用 Spring Data Rest 写WebApi 遇到Put请求后报415 Mieda Type 的错误,GG了下 找到个解决办法 ,下面是针对Put请求的过滤。
1 public class HttpPutRestfulContentFilter extends OncePerRequestFilter { 2 3 private Charset charset = Charset.forName("UTF-8"); 4 private final String method="PUT"; 5 6 @Override 7 protected void doFilterInternal(final HttpServletRequest request, HttpServletResponse response, 8 FilterChain filterChain) throws ServletException, IOException { 9 10 if (this.method.equals(request.getMethod())) { 11 HttpInputMessage inputMessage = new ServletServerHttpRequest(request) { 12 @Override 13 public InputStream getBody() throws IOException { 14 return request.getInputStream(); 15 } 16 }; 17 18 HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, this.method); 19 filterChain.doFilter(wrapper, response); 20 } 21 else { 22 filterChain.doFilter(request, response); 23 } 24 } 25 26 private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper { 27 28 private final String method; 29 30 public HttpMethodRequestWrapper(HttpServletRequest request, String method) { 31 super(request); 32 this.method = method; 33 } 34 35 @Override 36 public String getMethod() { 37 return this.method; 38 } 39 } 40 }
需要在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>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。