SpringMVC 配置处理器适配器,设置消息转换器,回写对象或集合报406

1.先看xml配置

<!--配置处理器适配器-->
<bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <!--配置消息转换器,指定以jacson来把返回的对象或集合转换为json字符串-->
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
        </list>
    </property>
</bean>
复制代码

2.控制层代码

//回写集合
@RequestMapping(value = "/quick12",produces = "text/html; charset=utf-8")
@ResponseBody //告诉SpringMvc框架,不进行视图跳转,只回写数据
public List<User> hello12() throws Exception {
    ArrayList<User> users = new ArrayList<>();
    Collections.addAll(users,new User("李四", '女'),new User("王五",'男'));
    return users;
}
复制代码

3.测试

image.png

4.解决

经查阅,报406是因为服务端响应的数据不被客户端所接收。

此时,尝试去掉@RequstMapping注解的属性produces设置的响应内容类型,如:

@RequestMapping(value = "/quick12")
复制代码

再测试:

image.png

问题解决。

5.分析

打开F12,查看响应头

image.png
可以发现,SpringMVC帮我们把对象或集合转为json时,会自动指定Content-Typeapplication/json;charset=UTF-8
此时如果我们在@RequstMapping的produces属性又指定一遍,则会覆盖,导致客户端无法接收,从而报406

6.总结

如果使用SpringMVC帮我们将对象或集合返回给客户端,最好的方式就是不指定任何Context-Type,不会报406,中文也不会乱码

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享