JavaWeb 开发遇到各种中文乱码,现统一整理出相应的解决方法。
前提要求是项目工程统一使用UTF-8
编码。
JSP页面统一UTF-8
编码
//指定jsp编译成 Servlet 时使用UTF-8编码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
...........
//指定 html 内容以 UTF-8 编码(不是页面文件编码)
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
get
提交数据,Java 代码添加对中文的字符转码
String name = new String(req.getParameter("name").getBytes("iso-8859-1"), "utf-8");
web.xml
添加编码过滤器,对POST
提交有效
<filter>
<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
编码过滤器相当于设置request
和response
的编码:
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
Tomcat配置文件server.xml
设置UTF-8
对URI进行UTF-8编码
,对GET
提交有效。
在Connector
标签增加URIEncoding="UTF-8"
设置。
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="80" protocol="HTTP/1.1" redirectPort="8443"/>`
springmvc.xml
添加消息转换器,指定编码格式
SpringMVC使用@ResponseBody
返回的String
消息中含有中文显示乱码
<!-- 注解驱动 -->
<mvc:annotation-driven>
<!-- HTML 消息转换 utf-8 -->
<mvc:message-converters register-defaults="true">
<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>
</mvc:message-converters>
</mvc:annotation-driven>
URL带参重定向中文乱码
- SpringMVC 在 Controller 之间带有模型封装的参数进行重定向,参数包含中文。
- 参数会拼接在重定向的
URL
上(get带参请求),但是URL
的中文会乱码,页面中文显示乱码。
解决:添加编码过滤器,UTF-8
编码,解决URL
乱码;在目标Controller 方法里将将传递的中文参数取出进行iso-8859-1
转UTF-8
,再把转码后的中文参数用model
封装。
中文写入数据库乱码
- 数据库和表及字段设置
utf-8
。 - 数据库连接设置编码:
jdbc:mysql://localhost:3306/anqi_test2?characterEncoding=utf-8&allowMultiQueries=true
SpringMVC国际化中文乱码
Spring MVC国际化时,从语言资源文件读取中文显示会乱码, 解决步骤如下:
- JSP文件统一
UTF-8
编码。 properties
文件统一UTF-8
编码。- 在
springmvc.xml
文件配置ResourceBundleMessageSource
时,添加支持中文的编码。实际是统一编码格式。
<!-- 国际化 -->
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<!-- 国际化资源文件名 -->
<property name="basenames" value="message"></property>
<!-- 支持UTF-8的中文 -->
<property name="cacheSeconds" value="0"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
[参考]http://blog.csdn.net/fancylovejava/article/details/7700683
更多内容请访问:IT源点
注意:本文归作者所有,未经作者允许,不得转载