MVC仅使用ContentNegotiationManagerF

MVC仅使用ContentNegotiationManagerF

本文介绍了Spring MVC仅使用ContentNegotiationManagerFactoryBean返回json 406的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于将http://localhost:8090/home/home/home2用作servlet上下文作为"home"的任何请求,我只希望转向JSON响应.

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".

我设置的配置是,如果没有接受标头,则将默认值返回为"JSON"响应.我也试图将接受类型设置为"application/json",这是行不通的.

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.

位于 Spring MVC + JSON = 406不可接受的解决方案是我尝试通过ContentNegotiationManagerFactoryBean类尝试使用Messageconverter的另一种方法.

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

web.xml如下

<?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>

servlet-context.xml如下.

<?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>

Java代码如下:

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;
    }

}

推荐答案

如果使用@ResponseBody或@RequestBody,则表示Spring 消息转换机制将被激活,并且ContentNegotiationManager无法控制.

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.

但是为什么MappingJackson2HttpMessageConverter(或早期版本的MappingJacksonHttpMessageConverter)不起作用?我猜您忘了添加杰克逊图书馆:

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>

这篇关于Spring MVC仅使用ContentNegotiationManagerFactoryBean返回json 406的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 03:57