Spring Boot 2.7插入含特殊字符作者名触发SQL异常求助
问题描述
Spring 6环境下项目运行正常,但切换到Spring Boot 2.7.15(对应Spring 5)后,插入包含特殊字符的作者名(如Niccolò)时触发SQL异常:
2023-09-15 11:01:50.754 WARN 28709 --- [nio-8080-exec-8] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1366, SQLState: HY000 2023-09-15 11:01:50.754 ERROR 28709 --- [nio-8080-exec-8] o.h.engine.jdbc.spi.SqlExceptionHelper : Incorrect string value: '\xEF\xBF\xBD' for column 'name' at row 1 2023-09-15 11:01:50.767 ERROR 28709 --- [nio-8080-exec-8] o.s.b.w.servlet.support.ErrorPageFilter : Forwarding to error page from request [/addAuthors] due to exception [could not execute statement; nested exception is org.hibernate.exception.GenericJDBCException: could not execute statement]
控制台输出作者名时显示为Niccol�,尝试手动转码后变为Niccol?,无法解决问题。
解决方案
1. 修正数据库连接URL的编码参数
在application.properties中,给数据库URL添加UTF-8编码相关参数,使用utf8mb4支持完整Unicode字符:
spring.datasource.url=jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf8mb4&serverTimezone=UTC
utf8mb4是MySQL真正支持全UTF-8的字符集,能覆盖特殊拉丁语系字符在内的所有Unicode字符。
2. 强制HTTP请求响应编码为UTF-8
在application.properties中添加以下配置,确保Spring Boot处理请求和响应时统一使用UTF-8:
spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true spring.http.encoding.force=true server.tomcat.uri-encoding=UTF-8
Spring Boot 2.x虽默认UTF-8,但部分表单提交场景可能出现编码丢失,强制编码可从源头避免该问题。
3. 配置Hibernate生成表的字符集
添加Hibernate连接编码参数,确保自动生成的表和字段使用utf8mb4字符集:
spring.jpa.properties.hibernate.connection.characterEncoding=utf8mb4 spring.jpa.properties.hibernate.connection.useUnicode=true
配合spring.jpa.hibernate.ddl-auto=create-drop,Hibernate生成表时会自动应用正确的字符集。
4. 确保Thymeleaf模板编码正确
如果使用Thymeleaf渲染表单页面,添加模板编码配置:
spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.mode=HTML
同时确保前端页面的<meta>标签声明UTF-8:
<meta charset="UTF-8">
5. 移除代码中的手动转码逻辑
代码中的手动转码会破坏原有编码结构,直接删除即可:
// 删除以下无效转码代码 byte[] bytes = name.getBytes(StandardCharsets.ISO_8859_1); name = new String(bytes, StandardCharsets.UTF_8);
验证方案
- 重启应用,提交包含特殊字符的作者名(如Niccolò)到
/addAuthors接口 - 检查控制台输出是否显示正确字符
- 查看数据库中
name字段是否正确存储该字符
内容的提问来源于stack exchange,提问作者Niccolò Balzarotti
相关产品推荐
相关产品推荐

