I want my controller to always work with JSON when handling exceptions

I centralized exception handling for my leisure service in a neat ControllerAdvice.

I return regular wrapping objects, in the hope that my cool display is the jackson converter, which will convert it to JSON for the end client.

Now here's the thing. If I do not set the accept-header to "Application / JSON", I do not get the converted JSON, instead I get the default HTML in my tests, which are apparently generated by Jetty. I have to admit that I'm not sure why, but I assume some default is Spring by default, which takes effect.

It made me think. Clients who call my vacation url should know that I am returning JSON, so I would like my service to always return json independently.

Is there a way to configure ReqeustMappingHandlerAdapter to always create JSON?

my current configuration:             

<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <beans:property name="messageConverters">
        <beans:list>
            <beans:ref bean="jsonConverter"/>
        </beans:list>
    </beans:property>
</beans:bean>

<!-- Instantiation of the converter  in order to configure it -->
<beans:bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <!--beans:property name="supportedMediaTypes" value="application/json"/-->
</beans:bean>
+4
source share
1 answer

I don't know if this answers your question, but you can set the default content type in your Spring configuration for JSON (the default is HTML without Accept header in Spring MVC). Here is an example configuration:

<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="defaultContentType" value="application/json" />
</bean>

<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" />

Source:

http://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc

+1
source

All Articles