控制台查询数据库中文打印显示正确,页面中文显示???;
在网上找了好多教程都没解决,最后发现是顺序问题。
1.如果是控制台查询数据打印问号
可以在Tomcat :VM options:加上 -Dfile.encoding=utf-8
2.页面显示问号
首先应该排除springmvc核心配置中是否配置了controller层的组件扫描,如果在spring核心配置中配置扫描,则需保证springmvc正常引入spring容器。
方法一:在@RequestMapping注解直接指定
@RequestMapping注解中添加:produces = "application/json;charset=utf-8"
@RequestMapping(value = "/demo",produces = "application/json;charset=utf-8")
方法二:在springmvc核心配置文件注解驱动中添加
它可以后台传输json回前台时,中文乱码问题,和上面效果基本一致,也是大部分人用的方法
<!--自定义消息转换器的编码,解决后台传输json回前台时,中文乱码问题,传回json字符串,非json对象,即页面响应头为
text/html;charset=UTF-8-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter" >
<property name = "supportedMediaTypes">
<list>
<value>application/json;charset=utf-8</value>
<value>text/html;charset=utf-8</value>
<value>application/x-www-form-urlencoded</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
方法三:配置处理器适配器(也是我遇到的问题)
这块有一个注意点,刚开始加上发现没有用,最后发现是因为
处理器适配器必须配置在注解驱动前才有效!!!
<!--处理器适配器必须配置在注解驱动前有效-->
<!--配置处理器适配器,返回json,-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</list>
</property>
</bean>
其他常见乱码情况配置
web.xml字符过滤配置
<!--encodingFilter-->
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
url配置(mysql8.0)
jdbc:mysql://localhost:3306/test?serverTimezone=GMT&allowPublicKeyRetrieval=true&useSSL=false&characterEncoding=utf8
再就是数据库的表编码是否是utf-8