多人 特别是新手 做j2ee 项目中
总能受困于 这样或那样的编码问题
这里讨论下 新手学习,高手指教 一起研究下
(以 tomcat mysql 做例子 我推荐所有的编码采用utf-8)
1 工程
工程内所有的 .java .jsp .xml .txt 都有默认的编码 默认的是系统环境的编码
我们中文系统通常是gbk 推荐都采用utf-8
utf-8 的时候 你编译 生成doc 可能会遇到乱码(特别是采用ant 的时候,生成doc你几乎100%会遇到)
解决方法 以ant 为例子
编译 注意 encoding 参数
<target name="build" >
<mkdir dir="${build.dir}" />
<javac encoding="utf-8" destdir="${build.dir}" target="1.3" debug="true" deprecation="false" optimize="false" failonerror="true">
<src path="${src.dir}" />
<classpath refid="master-classpath" />
</javac>
</target>
生成doc 注意 encoding 和 charset
<target name="doc">
<mkdir dir="doc" />
<javadoc charset="utf-8" encoding="utf-8" packagenames="${packages}" sourcepath="src" destdir="doc" author="true" version="true" use="true" splitindex="true" >
<classpath refid="master-classpath" />
</javadoc>
</target>
这里 的encoding 就是指的你 java 文件的编码格式 javac 和javadoc 都有这个参数
charset 指的是 生成 doc 后的编码方式 javadoc 的参数
2 数据库
mysql 的编码最复杂 从4以后 mysql 号称支持多编码 它更灵活了 我们也更麻烦了
mysql 有4个级别的编码
系统级
库级
表级
sql语句级
请保持采用统一的编码 推荐utf-8
其它数据库要简单的多 一般都是一种编码
3 web server
tomcat 为例
tomcat server.xml 中一个参数
<connectorport="8080" maxhttpheadersize="8192"
maxthreads="150" minsparethreads="25" maxsparethreads="75"
enablelookups="false" redirectport="8443" acceptcount="100"
connectiontimeout="20000" disableuploadtimeout="true" urincoding="utf-8"/>
经测试 这个urincoding 参数主要是 get 方法中采用编码
4 jsp 显示层
第1条中说明了 jsp 文件本身的格式
很多朋友采用eclipse +myeclipse 生成jsp
它自动生成一个头<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
不要误解 这句话不能保证你在ie里看到的不是乱码
pageencoding它的意思是 这个页面本身采用的是 utf-8 (似乎只在eclipse 里有效果 ,我不确定)
为了在ie 里不乱码 你还得加一句 <%@ page contenttype="text/html; charset=utf-8"%>
它不能在(myeclispe)自动生成 推荐修改 myeclipse的模板 在下边的目录里
myeclipse/eclipse/plugins/com.genuitec.eclipse.wizards_4.0.1/templates
里边的jsp模版 你加上<%@ page contenttype="text/html; charset=${encoding}"%>
5 filter
自从tomcat 4 以后 网上就流传了一个setcharacterencodingfilter 过滤器 搜一下有很多
很好用 web.xml 中加入
<filter>
???? <filter-name>set character encoding</filter-name>
???? <filter-class>filters.setcharacterencodingfilter</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>
6 资源文件
首先保证 文件本身是utf-8
然后部署的时候用 native2ascii 转换
这里给出 ant 里的例子
<native2ascii encoding="utf-8" dest="${web.dir}/web-inf/classes" src="${src.dir}" includes="**/*.properties" />
闽公网安备 35060202000074号