package common; import java.io.*;public class CodeFilter{ public CodeFilter() {} public static String change(String s) { s = toHtml(s); return s; } //特殊字符转为Html public static String toHtml(String s) { s = Replace(s,"&","&"); s = Replace(s,"<","<"); s = Replace(s,">",">"); s = Replace(s,"\t"," "); s = Replace(s,"\r\n","\n"); s = Replace(s,"\n","<br/>"); s = Replace(s," "," "); s = Replace(s,"'","'"); s = Replace(s,"\\","\"); return s; } //逆 public static String unHtml(String s){ s = Replace(s,"<br/>","\n"); s = Replace(s," "," "); return s; }
//Replace public static String Replace(String source,String oldString,String newString) { if(source == null) return null; StringBuffer output = new StringBuffer(); int lengOfsource = source.length(); int lengOfold = oldString.length(); int posStart = 0; int pos; while((pos = source.indexOf(oldString,posStart)) >= 0) { output.append(source.substring(posStart,pos)); output.append(newString); posStart = pos + lengOfold; } if(posStart < lengOfsource) { output.append(source.substring(posStart)); } return output.toString(); }}用上面的方法格式化一下你的字符串就行
把"<"号替换成"<"
把"&"号替换成"&"
空格替换成" "
把回车符"\n"替换成"<br>"
把双引号替换成"""
就是用xunyiren(从jsp开始)
说的方法
import java.io.*;public class CodeFilter{
public CodeFilter() {}
public static String change(String s) {
s = toHtml(s);
return s;
} //特殊字符转为Html
public static String toHtml(String s) {
s = Replace(s,"&","&");
s = Replace(s,"<","<");
s = Replace(s,">",">");
s = Replace(s,"\t"," ");
s = Replace(s,"\r\n","\n");
s = Replace(s,"\n","<br/>");
s = Replace(s," "," ");
s = Replace(s,"'","'");
s = Replace(s,"\\","\");
return s;
}
//逆
public static String unHtml(String s){
s = Replace(s,"<br/>","\n");
s = Replace(s," "," ");
return s;
}
//Replace
public static String Replace(String source,String oldString,String newString) {
if(source == null) return null;
StringBuffer output = new StringBuffer();
int lengOfsource = source.length();
int lengOfold = oldString.length();
int posStart = 0;
int pos;
while((pos = source.indexOf(oldString,posStart)) >= 0) {
output.append(source.substring(posStart,pos));
output.append(newString);
posStart = pos + lengOfold;
}
if(posStart < lengOfsource) {
output.append(source.substring(posStart));
}
return output.toString();
}}用上面的方法格式化一下你的字符串就行