本文转载自:http://www.host01.com/article/jsp/00040005/057211180557767.htm
在类似留言板的web应用中,需要将<textarea>中的大段文字显示在Jsp页面上,因此需要对文字中的特殊字符如换行、空格的作处理,方法如下:
1、直接保存,然后当从数据库中取出来时用过滤方法过滤一遍再送回页面即可,给一段代码,看了就明白了,可以自己扩充
public static String filter(String value) {
if (value == null)
return (null);
StringBuffer result = new StringBuffer();
for (int i = 0; i < value.length(); i++) {
char ch = value.charAt(i);
if (ch == '<')
result.append("<");
else if (ch == '>')
result.append(">");
else if (ch == '&')
result.append("&");
else if (ch == '"')
result.append(""");
else if (ch == '/r')
result.append("<BR>");
else if (ch == '/n') {
if (i > 0 && value.charAt(i - 1) == '/r') {
} else {
result.append("<BR>");
}
} else if (ch == '/t')
result.append("  ");
else if (ch == ' ')
result.append(" ");
else
result.append(ch);
}
return (result.toString());
}
2、在action中用replaceAll()把空格回车替换出来,
replaceAll(“/r/n“,“<br>“);
replaceAll(“ “,“/b“);
在jsp页面中,如果用<bean:write>则加上filter="false",
<bean:write name="info" property="content" filter="false"/>
3、利用样式表,在显示页面中放置一个“透明”的<textarea>,即边框颜色和文本框颜色都与背景颜色一致的文本框,然后将要显示的内容放置到该文本框中,这样不需要做任何处理,而且绝对和用户输入的格式一模一样,个人认为是最好的方法。当然,千万要记住把这个文本框设置成只读的啊,嘿嘿
4、【可以把<bean:write>用<pre></pre>包围起来,这样里边的东西就可以源源本本显示,
即使里边有换行或者HTML标签都可以源源本本显示,不用自己去查找变换。
不过也有点小毛病,就是显示的字体大小跟一般的字比起来小一点,再用<big></big>
包围以下就正常了。
最终结果就是
<pre><big><bean:write xxxxxxx /></big></pre>
试试看】
不应该用<pre>,<pre>不能与处理HTML标签,应该用<xmp>,
应该这样写:
<big>
<xmp><bean:write xxx /></xmp>
</big>