JavaWeb中文乱码解决统一记录

star2017 1年前 ⋅ 291 阅读

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>

编码过滤器相当于设置requestresponse的编码:

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带参重定向中文乱码

  1. SpringMVC 在 Controller 之间带有模型封装的参数进行重定向,参数包含中文。
  2. 参数会拼接在重定向的URL上(get带参请求),但是URL的中文会乱码,页面中文显示乱码。
    解决:添加编码过滤器,UTF-8编码,解决URL乱码;在目标Controller 方法里将将传递的中文参数取出进行iso-8859-1UTF-8,再把转码后的中文参数用model封装。

中文写入数据库乱码

  1. 数据库和表及字段设置utf-8
  2. 数据库连接设置编码:jdbc:mysql://localhost:3306/anqi_test2?characterEncoding=utf-8&allowMultiQueries=true

SpringMVC国际化中文乱码

Spring MVC国际化时,从语言资源文件读取中文显示会乱码, 解决步骤如下:

  1. JSP文件统一UTF-8编码。
  2. properties文件统一UTF-8编码。
  3. 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源点

相关文章推荐

全部评论: 0

    我有话说: