Unicode在多语言环境的应用(JSP)
Windows(2000以后)的内码是Unicode,它在技术上可以同时支持多个代码页。(所谓代码页(code page)就是针对一种语言文字的字符编码。)只要文件能说明自己使用什么编码,用户又安装了对应的代码页,Windows就能正确显示,例如在HTML文件中就可以指定Charest。
Unicode是一种可以容纳全世界所有语言文字的编码方案。在多语言网页的开发中就显得尤为重要了。为了保证网页的正常使用,在J2EE开发中,以下工作是需要保证的:
1) 为了保证从Client发送到Server的数据的编码方式是我们所需要的。并且Server到Client的数据能正常的显示。根据W3标准文档的说明及前文的分析,在JSP文件中需要指定字符集为UTF-8。即在JSP的头部添加如下字样:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
2)所有的JAVA 和JSP 以及properties、xml 等等本工程用到的文件的编码方案都为Unicode。注:有些Web服务器会把非Unicode编码的JAVA文件编译成Unicode的Class文件。
3)如果应用到数据库,那么数据的Encoding应该为UTF-8。
4)需要在web.xml文件中添加过滤器,将所有的request的Encoding设置为Unicode 。
具体步骤如下:
A。 Xml文件的配置
<filter>
<description>Encode request</description>
<display-name>Encode Filter</display-name>
<filter-name>Encode Filter</filter-name>
<filter-class>
unicodetest.SetEncode
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Encode Filter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
这里<url-pattern>*.do</url-pattern>是已struts为例子的,在Struts里,所有的请求都有.do字样。如果是其他的模式,可以根据请求的情况,具体改变
B。 unicodetest。SetEncode类的具体代码
package unicodetest; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class SetEncode implements Filter { private String encoding; public void init(FilterConfig filterConfig) throws ServletException { this.encoding = filterConfig.getInitParameter("encoding"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding(this.encoding); chain.doFilter(request, response); } public void destroy() { }
希望这个对大家有一点帮助。