SSM框架响应中文乱码解决方案

SSM框架响应出现中文乱码解决方案

问题描述: 使用SSM框架测试代码时,偶然间发现响应中文出现乱码,但是我项目中使用UTF-8的编码格式,并且在web.xml 中也采用了utf-8的编码过滤,依然出现响应中文乱码问题感到费解。如图所示:
在这里插入图片描述在这里插入图片描述运行后中文乱码:
在这里插入图片描述
问题出现原因:

1.虽然已经在web.xml 中也采用了utf-8的编码过滤,而控制台显示“text/plain”显然是有问题的。

在这里插入图片描述

2.通过查阅资料发现在其对应org.springframework.http.converter.StringHttpMessageConverter方法中使用的是默认字符集是ISO-8859-1编码,如图
在这里插入图片描述

在这里插入图片描述

因此导致响应中文时出现乱码问题。

解决方案:

需要将StringHttpMessageConverter的编码方式改为UTF-8。

方式一:在@RequestMapping里面加入produces = “text/html;charset=UTF-8” 。采用这种方式如果每个@RequestMapping里面都添加一个显然是不太友好的,那么推荐使用方式二。

方式二:直接将org.springframework.http.converter.StringHttpMessageConverter 里面的属性defaultCharset设置成utf-8。

如下设置在spring-mvc.xml 中

<!--自定义消息转换器的编码,解决后台传输json回前台时,中文乱码问题 -->
<bean id="stringHttpMessageConverter"
class="org.springframework.http.converter.StringHttpMessageConverter">
	<constructor-arg value="UTF-8" />
</bean>
 
<mvc:annotation-driven>
	<mvc:message-converters>
		<ref bean="stringHttpMessageConverter" />
	</mvc:message-converters>
</mvc:annotation-driven>

再次测试:问题解决。
在这里插入图片描述

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
如果在SSM项目的MyBatis中出现中文乱码问题,可以尝试以下解决方法: 1. 在MyBatis的配置文件中,添加以下属性: ``` <configuration> <settings> <setting name="jdbcTypeForNull" value="NULL" /> <setting name="mapUnderscoreToCamelCase" value="true" /> <setting name="defaultExecutorType" value="SIMPLE" /> <setting name="lazyLoadingEnabled" value="true" /> <setting name="aggressiveLazyLoading" value="true" /> <setting name="autoMappingBehavior" value="PARTIAL" /> <setting name="logImpl" value="LOG4J" /> <setting name="localCacheScope" value="SESSION" /> <setting name="jdbcTypeForNull" value="NULL" /> <setting name="useGeneratedKeys" value="true" /> <setting name="defaultStatementTimeout" value="25000" /> <setting name="defaultFetchSize" value="100" /> <setting name="cacheEnabled" value="true" /> <setting name="defaultExecutorType" value="REUSE" /> <setting name="useColumnLabel" value="true" /> <setting name="useActualParamName" value="true" /> </settings> </configuration> ``` 其中,`useColumnLabel`和`useActualParamName`都设置为`true`,可以解决中文乱码的问题。 2. 在数据库连接的URL中,添加以下参数: ``` useUnicode=true&characterEncoding=utf-8 ``` 例如: ``` jdbc:mysql://localhost:3306/mydatabase?useUnicode=true&characterEncoding=utf-8 ``` 这样可以确保数据库连接的字符集为UTF-8,避免中文乱码问题。 3. 在实体类中,为中文属性添加`@Column`注解,并设置`columnDefinition`属性为`text`,例如: ``` @Column(columnDefinition = "text") private String name; ``` 这样可以确保数据库表中的字段类型为`text`,避免中文乱码问题。 总之,解决中文乱码问题需要确保MyBatis、数据库连接和实体类中的字符集都是UTF-8,同时将`useColumnLabel`和`useActualParamName`设置为`true`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值