Fork me on GitHub

配置JSON视图406问题

The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ().

http://stackoverflow.com/questions/3340050/springs-json-not-being-resolved-with-appropriate-response
http://stackoverflow.com/questions/7462202/spring-json-request-getting-406-not-acceptable?lq=1
http://stackoverflow.com/questions/4856298/spring-mvc-3-returning-xml-through-responsebody

复制代码
  <!-- 配置JSON视图解析-->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" />
            </list>
        </property>
    </bean>
 
    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>application/json;charset=UTF-8</value>
            </list>
        </property>
    </bean>
 
    <!-- 或者配置JSON视图解析-->
 
    <bean id="jsonView"
        class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
        <property name="encoding">
            <value type="org.codehaus.jackson.JsonEncoding">UTF8</value>
        </property>
        <property name="contentType" value="text/html;charset=UTF-8" />
    </bean>    
    <mvc:annotation-driven />
复制代码

或者如官方文档所述

In Spring 3, you can enable “mvc:annotation-driven” to support object conversion to/from JSON format, if Jackson JSON processor is existed on the project classpath.

Add “@ResponseBody” in the return value, no much detail in the Spring documentation.

As i know, when Spring see

  1. Jackson library existed on classpath
  2. “mvc:annotation-driven” is enabled
  3. Return method annotated with @ResponseBody

It will handle the JSON conversion automatically.

Enable “mvc:annotation-driven” in your Spring configuration XML file

复制代码
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="com.mkyong.common.controller" />
    <mvc:annotation-driven />
 
</beans>
复制代码

 

如下面Code

复制代码
@Controller
@RequestMapping("/json")
public class JsonController {
    @RequestMapping("/view.shtml")
    public @ResponseBody
    User view() {
        User user = new User();
        user.setEmail("Irving_Zhou@outlook.com");
        user.setNickname("irving");
        user.setAdddate(new Date());
        return user;
    }

    @RequestMapping("/map.shtml")
    public @ResponseBody
    Map<String, Object> map() {
        User user = new User();
        user.setEmail("Irving_Zhou@outlook.com");
        user.setNickname("irving");
        user.setAdddate(new Date());
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("user", user);
        map.put("totle", 50);
        return map;
    }

    @RequestMapping("/list.shtml")
    public @ResponseBody
    List<User> list() {
        List<User> list = new ArrayList<User>();
        for (int i = 0; i < 3; i++) {
            User user = new User();
            user.setEmail("Irving_Zhou@outlook.com");
            user.setNickname("irving");
            user.setAdddate(new Date());
            list.add(user);
        }
        return list;
    }

    @RequestMapping("/listtest.shtml")
    public @ResponseBody
    List<User> listtest() {
        List<User> list = new ArrayList<User>();
        for (int i = 0; i < 3; i++) {
            User user = new User();
            user.setEmail("Irving_Zhou@outlook.com");
            user.setNickname("irving");
            user.setAdddate(new Date());
            user.setTruename("哈哈哈");
            list.add(user);
        }
        return list;
    }
}
复制代码

XML

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
                        http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.2.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!-- 注解驱动-->
    <mvc:annotation-driven />

    <!-- 扫描注解类 -->
    <context:component-scan base-package="cn.base.web.controller" />
    <context:component-scan base-package="cn.base.web.dao.impl" />
    <context:component-scan base-package="cn.base.web.service.impl" />
</beans>
复制代码

Just Test:

image

@ResponseBody乱码的解决方案

复制代码
<!--启动Spring MVC的注解功能,完成请求和注解POJO的映射并且设置ResponseBody返回编码 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" >
    <property name="messageConverters">   
         <list>   
             <bean class = "org.springframework.http.converter.StringHttpMessageConverter"> 
                <constructor-arg>
                    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
                        <property name="targetClass" value="java.nio.charset.Charset" />
                       <property name="targetMethod" value="forName"/>
                       <property name="arguments" value="UTF-8"/>
                    </bean>
                </constructor-arg>
            </bean>   
         </list>   
   </property>  
</bean>
复制代码
posted @   花儿笑弯了腰  阅读(808)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示