如何将Spring MVC的默认媒体类型从XML更改为JSON

时间:2010-09-01 16:49:06

标签: java xml json spring-mvc

标题几乎说明了一切。现在它在我的控制器的响应中使用XML作为默认值,但我希望它在没有指定Accepts头或格式参数时使用JSON作为默认值。

我的mvc-config.xml

<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
    <property name="mediaTypes">

        <map>
            <entry key="html" value="text/html" />
            <entry key="json" value="application/json" />
            <entry key="xml" value="application/xml" />
        </map>
    </property>
    <property name="defaultViews">
        <list>
            <bean class="com.work.web.view.json.ExtendedMappingJacksonJsonView">
                <property name="objectMapper">
                    <ref bean="JacksonObjectMapper" />
                </property>
            </bean>
            <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
                <property name="marshaller">
                    <ref bean="Jaxb2Marshaller" />
                </property>
            </bean>
        </list>
    </property>
    <property name="favorParameter" value="true" />
</bean>

<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean
                class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="objectMapper">
                    <ref bean="JacksonObjectMapper" />
                </property>
            </bean>
            <ref bean="marshallingHttpMessageConverter" />
        </list>
    </property>
</bean>

<bean id="marshallingHttpMessageConverter"
    class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
    <property name="marshaller" ref="Jaxb2Marshaller" />
    <property name="unmarshaller" ref="Jaxb2Marshaller" />
</bean>
<bean id="JacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="JacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
    factory-bean="JacksonObjectMapper" factory-method="getSerializationConfig" />
<bean
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject" ref="JacksonSerializationConfig" />
    <property name="targetMethod" value="setSerializationInclusion" />
    <property name="arguments">
        <list>
            <value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_NULL</value>
        </list>
    </property>
</bean>
<bean id="Jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="classesToBeBound">
        <list>
            <value>com.work.Concepts</value>

        </list>
    </property>
</bean>

1 个答案:

答案 0 :(得分:4)

<property name="defaultContentType" value="application/json" />

设置ContentNegotiatingViewResolver bean时