在类似留言板的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>,即边框颜色和文本框颜色都与背景颜色一致的文本框,然后将要显示的内容放置到该文本框中,这样不需要做任何处理,而且绝对和用户输入的格式一模一样,个人认为是最好的方法。当然,千万要记住把这个文本框设置成只读的啊,嘿嘿 
|