分类: Java
2009-02-26 13:26:29
以前用java做WEB开发编写的转换代码,希望对大家有所帮助。
主要包括如下函数:
1. escapeJSValue: 转换为可以对Javascript变量赋值的文本
2. escapeFormValue:转换成可以对表单元素的value赋值的字符串
3. escapeHtmlValue:转换成HTML中显示的文本
4. escapeTextAreaValue:转换成textarea中的文本
//Javascript字符串转换,转换成Javascript中的字符串,用于对JS变量赋值
public static String escapeJSValue(String src)
{
if (src == null)
{
return null;
}
String szResult;
szResult = src;
szResult = szResult.replaceAll("", "");
szResult = szResult.replaceAll("", "");
szResult = szResult.replaceAll("", "");
szResult = szResult.replaceAll("'", "");
szResult = szResult.replaceAll("<", "");
szResult = szResult.replaceAll("\"", """);
return szResult;
}
//转换成HTML中可以对value赋值的字符串,用于对form中的元素赋值
public static String escapeFormValue(String src)
{
if (src == null)
{
return null;
}
int len = src.length();
StringBuffer sbResult = new StringBuffer(len);
char ch;
try
{
for (int i=0; i
ch = src.charAt(i);
switch(ch)
{
case '\"':
sbResult.append(""");
break;
case '&':
sbResult.append("&");
break;
case '>':
sbResult.append(">");
break;
case '<':
sbResult.append("<");
break;
case '\n':
sbResult.append("
");
break;
case '\r':
sbResult.append("
");
break;
default:
sbResult.append(ch);
break;
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return sbResult.toString();
}
//转换成HTML中显示的文字
public static String escapeHtmlValue(String src)
{
if (src == null)
{
return null;
}
int len = src.length();
StringBuffer sbResult = new StringBuffer(len);
char ch;
boolean bPreviousIsSpace = false;
try
{
for (int i=0; i
ch = src.charAt(i);
switch(ch)
{
case '&':
sbResult.append("&");
bPreviousIsSpace = false;
break;
case '>':
sbResult.append(">");
bPreviousIsSpace = false;
break;
case '<':
sbResult.append("<");
bPreviousIsSpace = false;
break;
case ' ':
if (!bPreviousIsSpace)
{
sbResult.append(ch);
bPreviousIsSpace = true;
}
else
{
sbResult.append(" ");
}
break;
default:
sbResult.append(ch);
bPreviousIsSpace = false;
break;
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return sbResult.toString();
}
public static String escapeHtmlValue2(String src)
{
if (src == null)
{
return null;
}
String szResult = escapeHtmlValue(src);
szResult = szResult.replaceAll("", "
");
szResult = szResult.replaceAll("", "
");
return szResult.replaceAll("", " ");
}
//转换成Textarea中的文字
public static String escapeTextAreaValue(String src)
{
if (src == null)
{
return null;
}
int len = src.length();
StringBuffer sbResult = new StringBuffer(len);
char ch;
try
{
for (int i=0; i
ch = src.charAt(i);
switch(ch)
{
case '&':
sbResult.append("&");
break;
case '>':
sbResult.append(">");
break;
case '<':
sbResult.append("<");
break;
default:
sbResult.append(ch);
break;
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return sbResult.toString();
}