Java字符编码解析 (四)

2014-11-24 11:17:39 · 作者: · 浏览: 22
sed in parsing the
* incoming request
*/
public class SetCharacterEncodingFilter
implements Filter {
public SetCharacterEncodingFilter()
{}
protected boolean debug = false;
protected String encoding = null;
protected FilterConfig filterConfig = null;
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}

public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// if (request.getCharacterEncoding() == null)
// {
// String encoding = getEncoding();
// if (encoding != null)
// request.setCharacterEncoding(encoding);
//
// }
request.setCharacterEncoding(encoding);
if ( debug ){
System.out.println( ((HttpServletRequest)request).getRequestURI()+"setted to "+encoding );
}
chain.doFilter(request, response);
}

public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
this.debug = "true".equalsIgnoreCase( filterConfig.getInitParameter("debug") );
}

protected String getEncoding() {
return (this.encoding);
}
}
web.xml中加入:


[html]

LocalEncodingFilter
LocalEncodingFilter
com.ccb.ectipmanager.request.SetCharacterEncodingFilter

encoding
gb2312


debug
false




LocalEncodingFilter
/*


LocalEncodingFilter
LocalEncodingFilter
com.ccb.ectipmanager.request.SetCharacterEncodingFilter

encoding
gb2312


debug
false




LocalEncodingFilter
/*

5 用于Weblogic(vedor-specific):

其一:在web.xml里加上如下脚本:


[html]

weblogic.httpd.inputCharset./*
GBK


weblogic.httpd.inputCharset./*
GBK


其二(可选)在weblogic.xml里加上如下脚本:


[html]


/*
GBK



/*
GBK


SWING/AWT/SWT
对于SWING/AWT,Java会有些缺省字体如Dialog/San Serif,这些字体到系统真实字体的映射在$JRE_HOME/lib/font.properties.XXX文件中指定。排除字体显示问题时,首先需要确定JVM的区域为zh_CN,这样font.properties.zh_CN文件才会发生作用。对于 font.properties.zh_CN , 需要检查是否映射缺省字体到中文字体如宋体。

在Swing中,Java自行解释TTF字体,渲染显示;对于AWT,SWT显示部分交由操作系统。首先需要确定系统装有中文字体。

1 汉字显示为”□”,一般为显示字体没有使用中文字体,因为Java对于当前字体显示不了的字符,不会像Windows一样再采用缺省字体显示。

2 部分不常见汉字不能显示,一般为显示字库中汉字不全,可以换另外的中文字体试试。

3 对于AWT/SWT,首先确定JVM运行环境的区域设置为中文,因为此处设计JVM与操作系统api调用的转换问题,再检查其它问题。

JNI
JNI中jstring以UTF-8编码给我们,需要我们自行转为本地编码。对于Windows,可以采用WideCharToMultiByte/MultiByteToWideChar函数进行转换,对于Unix,可以采用iconv库。

这里从SUN jdk 1.4 源代码中找到一段使用jvm String 对象的getBytes的转换方式,相对简单和跨平台,不需要第三方库,但速度稍慢。函数原型如下:


[cpp]
/* Convert between Java strings and i18n C strings */
JNIEXPORT jstring
NewStringPlatform(JNIEnv *env, const char *str);

JNIEXPORT const char *
GetStringPlatformChars(JNIEnv *env, jstring jstr, jboolean *isCopy);

JNIEXPORT jstring JNICALL
JNU_NewStringPlatform(JNIEnv *env, const char *str);

JNIEXPORT const char * JNICALL
JNU_GetStringPlatformChars(JNIEnv *env, jstring jstr, jboolean *isCopy);

JNIEXPORT void JNICALL
JNU_ReleaseStringPlatformChars(JNIEnv *env, jstring jstr, const char *st