Spring MVC 中解决中文乱码问题

在 Spring MVC 中解决中文乱码问题,需要从 请求参数编码响应内容编码 两方面入手。以下是完整的解决方案:


一、解决请求参数中文乱码

1. POST 请求编码(表单提交)

配置 CharacterEncodingFilter

web.xml 中添加 Spring 提供的字符编码过滤器,强制请求和响应使用 UTF-8 编码:

xml 复制代码
<!-- 解决 POST 请求中文乱码 -->
<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param> 
</filter>
<filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
2. GET 请求编码(URL 参数)

修改 Tomcat 的 server.xml

在 Tomcat 的 conf/server.xml 文件中,找到 Connector 配置,添加 URIEncoding="UTF-8"

xml 复制代码
<Connector 
    port="8080" 
    protocol="HTTP/1.1"
    URIEncoding="UTF-8"  <!-- 关键配置 -->
    connectionTimeout="20000"
    redirectPort="8443" />

二、解决响应内容中文乱码

1. 配置消息转换器(JSON 响应)

在 Spring MVC 配置文件中(如 spring-mvc.xml),设置 MappingJackson2HttpMessageConverter 的默认编码:

xml 复制代码
<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>text/plain;charset=UTF-8</value>
                    <value>text/html;charset=UTF-8</value>
                </list>
            </property>
        </bean>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>application/json;charset=UTF-8</value>
                </list>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
2. 全局响应编码配置

web.xml 中添加响应编码过滤器:

xml 复制代码
<filter>
    <filter-name>responseFilter</filter-name>
    <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>responseFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

三、其他注意事项

1. JSP 页面编码设置

确保 JSP 页面头部声明了 UTF-8 编码:

jsp 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
2. 数据库连接编码

如果涉及数据库操作,在 JDBC URL 中指定字符集:

properties 复制代码
jdbc.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8
3. Ajax 请求编码

对于前端 Ajax 请求(如 jQuery),显式设置 contentType

javascript 复制代码
$.ajax({
    url: '/api/data',
    type: 'POST',
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8', // 明确设置编码
    data: { name: '张三' },
    success: function(response) {
        console.log(response);
    }
});

四、验证配置是否生效

  1. POST 请求测试

    提交表单后,观察后端是否能正确接收中文参数。

  2. GET 请求测试

    访问带中文参数的 URL,如 http://localhost:8080/user?name=张三,检查是否乱码。

  3. 响应内容测试

    返回 JSON 数据或视图页面,确认中文字符正常显示。


五、常见问题排查

  1. 乱码仅在部分场景出现

    • 检查是否遗漏了 GET 请求的 Tomcat 配置。
    • 确认前端请求头 Content-Type 是否携带 charset=UTF-8
  2. Spring Boot 项目配置

    application.properties 中添加:

    properties 复制代码
    server.servlet.encoding.force=true
    server.servlet.encoding.charset=UTF-8
  3. Tomcat 9+ 的兼容性

    新版 Tomcat 默认使用 UTF-8 编码,但仍需确保 URIEncoding 配置正确。


通过以上步骤,可以彻底解决 Spring MVC 中的中文乱码问题!

相关推荐
J_bean42 分钟前
Spring AI Alibaba 项目接入兼容 OpenAI API 的大模型
人工智能·spring·大模型·openai·spring ai·ai alibaba
柳贯一(逆流河版)3 小时前
Spring 三级缓存:破解循环依赖的底层密码
java·spring·缓存·bean的循环依赖
蚰蜒螟7 小时前
Spring 和 Lettuce 源码分析 Redis 节点状态检查与失败重连的工作原理
java·redis·spring
神仙别闹7 小时前
基于 JSP+Mysql实现MVC房屋租赁系统
java·mysql·mvc
duration~7 小时前
SpringAI集成MCP
人工智能·后端·spring·ai
悟纤7 小时前
Spring Boot 实用小技巧:多级缓存(Caffeine + Redis)- 第545篇
spring boot·后端·spring
励志成为糕手7 小时前
企业级Spring事务管理:从单体应用到微服务分布式事务完整方案
分布式·spring·微服务·隔离级别·事务管理
Dajiaonew14 小时前
Spring AI RAG 检索增强 应用
java·人工智能·spring·ai·langchain
Java小白程序员1 天前
Spring Framework :IoC 容器的原理与实践
java·后端·spring
小李是个程序1 天前
登录与登录校验:Web安全核心解析
java·spring·web安全·jwt·cookie