Spring MVC return json only 406 with ContentNegoti

2019-08-06 11:12发布

问题:

I want only JSON response to be turned for any request that is made to http://localhost:8090/home/home/home2 for a servlet context as "home".

The configuration that I have set is to return default as "JSON" response if there are no accept headers. I have also tried to set the accept type to "application/json" , which is not working.

The solution over at Spring MVC + JSON = 406 Not Acceptable is with a different approach of Messageconverter, while I am trying through ContentNegotiationManagerFactoryBean class.

The web.xml is as follows

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

The servlet-context.xml is as follows.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.andy.main" />


    <resources mapping="/resources/**" location="/resources/" />



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

        <beans:property name="mediaTypes">
            <beans:map>
                <beans:entry key="json" value="application/json" />
                <beans:entry key="xml" value="application/xml" />
        </beans:map>
    </beans:property>
    </beans:bean>

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


</beans:beans>

The java code is as follows:

package com.andy.main;

import java.util.HashMap;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Handles requests for the application home page.
 */
@Controller
@RequestMapping("/home")
public class HomeController {

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    /**
     * Simply selects the home view to render by returning its name.
     */
    @RequestMapping(value = "/home2" , method = RequestMethod.GET)
    public  @ResponseBody HashMap<String, String> home(Locale locale, Model model) {
        System.out.println("In Home2");
        logger.info("Welcome home! The client locale is {}.", locale);
        HashMap<String, String> allValues=new HashMap<String, String>();
        allValues.put("Doctor","Dr.John");
        allValues.put("Location", "location1");
        return allValues;
    }

}

回答1:

If you use @ResponseBody or @RequestBody it means that Spring Message Conversions mechanism will be activated by default, and your ContentNegotiationManager doesn't get control.

But why MappingJackson2HttpMessageConverter (or previous version MappingJacksonHttpMessageConverter) doesn't work? I guess that you forgot to add jackson library:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.4</version>
</dependency>