解决SpringMVC传输json数据时的乱码

今天在练习过程中遇到SringMVC传输中文乱码问题,找了很久才解决。

  • 数据库设置编码为UTF-8
  • eclipse工作区编码也是UTF-8,控制台打印出中文正常
  • jsp设置编码为UTF-8
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

js代码如下:

window.onload = function(){

        $.get('list/house.html', function (response, status, xhr) {
            alert(status);
            console.log(response);
        });

    };

但是显示中文变成了,后来找了很久才在这里找到解决办法。原文地址

具体是在springmvc.xml文件当中添加如下配置

<bean id="stringHttpMessageConverter"
    class="org.springframework.http.converter.StringHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/plain;charset=UTF-8value>
                <value>application/json;charset=UTF-8value>
            list>
        property>
    bean>
    
    
    <bean id="mappingJackson2HttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>application/json;charset=UTF-8value>
                <value>application/xml;charset=UTF-8value>
                <value>text/html;charset=UTF-8value>
                <value>text/plain;charset=UTF-8value>
                <value>text/xml;charset=UTF-8value>
                <value>text/javascript;charset=UTF-8value>
            list>
        property>
    bean>
    <mvc:annotation-driven>
        <mvc:message-converters>
            <ref bean="stringHttpMessageConverter" />
            <ref bean="mappingJackson2HttpMessageConverter" />
        mvc:message-converters>
    mvc:annotation-driven>

问题解决。

你可能感兴趣的:(java,web知识积累)