日期:2014-05-18  浏览次数:20720 次

中文不能在facelets的xhtml的script中正常输出,中文显示#1213;#1322;之类的东西
所有文件格式及过滤器编码都是UTF-8,中文可以输出,但是页面脚本里面的中文不能输出如:alert( "你好 "),输出#1213;#1322;
这个问题该如何解决

------解决方案--------------------
需要javascript转码,转成\uXXXX的格式。参考以下代码:

public static String escapeJavaScript(String str)
{
if (str == null)
{
return null;
}

StringBuffer writer = new StringBuffer(str.length() * 2);

int sz = str.length();
for (int i = 0; i < sz; i++)
{
char ch = str.charAt(i);

// handle unicode
if (ch > 0xfff)
{
writer.append( "\\u "); //$NON-NLS-1$
writer.append(hex(ch));
}
else if (ch > 0xff)
{
writer.append( "\\u0 "); //$NON-NLS-1$
writer.append(hex(ch));
}
else if (ch > 0x7f)
{
writer.append( "\\u00 "); //$NON-NLS-1$
writer.append(hex(ch));
}
else if (ch < 32)
{
switch (ch)
{
case '\b ':
writer.append( '\\ ');
writer.append( 'b ');
break;
case '\n ':
writer.append( '\\ ');
writer.append( 'n ');
break;
case '\t ':
writer.append( '\\ ');
writer.append( 't ');
break;
case '\f ':
writer.append( '\\ ');
writer.append( 'f ');
break;
case '\r ':
writer.append( '\\ ');
writer.append( 'r ');
break;
default:
if (ch > 0xf)
{
writer.append( "\\u00 "); //$NON-NLS-1$
writer.append(hex(ch));
}
else
{
writer.append( "\\u000 "); //$NON-NLS-1$
writer.append(hex(ch));
}
break;
}
}
else
{
switch (ch)
{
case '\ ' ':
// If we wanted to escape for Java strings then we would
// not need this next line.
writer.append( '\\ ');
writer.append( '\ ' ');
break;
case ' " ':
writer.append( '\\ ');
writer.append( ' " ');
break;
case '\\ ':
writer.append( '\\ ');
writer.append( '\\ ');
break;
default:
writer.append(ch);
break;
}