Nitish Jain
Nitish Jain

Reputation: 734

how to return response with body in xml format from filter in springboot?

Unable to get the response with body in xml format from filter in springboot. I can get in JSON format correctly by using below code:

            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.reset();
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setHeader(HttpHeaders.CONTENT_TYPE, request.getHeader(HttpHeaders.ACCEPT));
            response.setContentType(request.getHeader(HttpHeaders.ACCEPT));
            objectMapper.writeValue(response.getWriter(), ErrorUtil.createErrorsVO(ErrorTypeEnum.HEADER_NOT_SET, INTUIT_OFFERING_ID));

Upvotes: 0

Views: 499

Answers (1)

Constantin Müller
Constantin Müller

Reputation: 1290

As I can see you're using Jackson already for serializing to JSON. I'd recommend to use the Jackson XML extension:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

Please note that this only works for Spring MVC out of the box. If you wish to use the XmlMapper, the counterpart of the ObjectMapper, in Spring Security, you have to inject a bean. Problem is, that Spring doesn't register a bean of type XmlMapper by default.

If you just want to use XML serialization you can do the following:

@Bean
@Primary
public XmlMapper xmlMapper(MappingJackson2XmlHttpMessageConverter converter) {
    return (XmlMapper) converter.getObjectMapper();
}

After this you can inject a bean of type XmlMapper in your filter.

EDIT

I answered first and then thought/researched. There already seems to be questions that deal with the problem, take a look at them:

Upvotes: 1

Related Questions