字符编码 Mysql, SpringMVC, GlashFish, Tomcat

(转自)http://hi.baidu.com/quest2run/blog/item/696488143eea1104c83d6da3.html

已经记不得自己最后一次解决这个问题是什么时候了,反正当时是觉得自己搞定啦,可是最近使用新的框架,新的 GlassFish 服务器,突然间又遇到这个问题,可是却一下想不起怎么解决了,看来“好心性不如烂笔头”啊。

1. 基本原则
在所有的层统一 encoding, 比如要做国际化的应用,那就是 UTF-8 了

2. Mysql
2.1 数据库配置 my.cnf 中
default-character-set=utf8

2.2 jdbc.url=jdbc:mysql://localhost:3306/study?useUnicode=true&characterEncoding=UTF-8

3. servlet container 或 Application Container
3.1 Tomcat   server.xml     

<Connector port="8080" maxHttpHeaderSize="8192"
               maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
               enableLookups="false" redirectPort="8443" acceptCount="100"
               connectionTimeout="20000" disableUploadTimeout="true"
               URIEncoding="UTF-8"
   />
3.2 GlassFish
默认情况是 UTF-8,但可是在 sun-web.xml 中加上
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD GlassFish Application Server 3.0 Servlet 3.0//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_3_0-0.dtd">
<sun-web-app error-url="">
<context-root>/study</context-root>
<class-loader delegate="true"/>
<jsp-config>
<property name="keepgenerated" value="true">
<description>Keep a copy of the generated servlet class' java code.</description>
</property>
</jsp-config>
<parameter-encoding default-charset="UTF-8"/>
</sun-web-app>

4. Servlet/Filter

web.xml

<!-- filter to set the encoding, the encoding should be consistent in all layers of the application -->
<filter>
<filter-name>Set Character Encoding</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>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

5. JSP/HTML page
5.1  JSP
<%@ page contentType="text/html;charset= UTF-8" %>
<%@page pageEncoding=" UTF-8"%>

5.2 HTML
<HEAD>
<TITLE>JPetStore Demo</TITLE>
<META content="text/html;charset= UTF-8" http-equiv=Content-Type>
</HEAD>


注意,mysql 官方公布了一些老的 connectJ 的 Bug, 不认 UTF-8, 只认 UTF8 (不带中画线的)

猜你喜欢

转载自chinaxxren.iteye.com/blog/1596914
今日推荐