Accepting / returning XML/JSON request and response - Spring MVC

前端 未结 5 759
無奈伤痛
無奈伤痛 2021-01-31 04:54

I need to write a rest service which accepts XML/JSON as a input (POST method) and XML/JSON as a output (based on the input format). I have tried a below approach to achieve thi

5条回答
  •  臣服心动
    2021-01-31 05:35

    Register a filter that intercepts each request, warp the HttpServletRequest into an implementation of HttpServletRequestWrapper and returns the Content-Type value for Accept header. For example, you can register a filter named SameInSameOutFilter like following:

    @Component
    public class SameInSameOutFilter extends GenericFilterBean {
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            SameInSameOutRequest wrappedRequest = new SameInSameOutRequest((HttpServletRequest) request);
            chain.doFilter(wrappedRequest, response);
        }
    }
    

    It wraps current request in a SameInSameOutRequest:

    public class SameInSameOutRequest extends HttpServletRequestWrapper {
        public SameInSameOutRequest(HttpServletRequest request) {
            super(request);
        }
    
        @Override
        public String getHeader(String name) {
            if (name.equalsIgnoreCase("accept")) {
                return getContentType();
            }
    
            return super.getHeader(name);
        }
    }
    

    This wrapper tells spring mvc to select a HttpMessageConverter based on request's Content-Type value. If request body's Content-Type is application/xml, then the response would be an XML. Otherwise, the response would be JSON.

    The other solution is to manually set the Accept header along with Content-Type in each request and avoid all these hacks.

提交回复
热议问题