JSP頁面里面的內(nèi)容往往是動態(tài)顯示,當(dāng)然也一般是從DB中按需取出來的了!
在顯示過程也許會碰到這樣的問題:
我們通過后臺操作將一些文字(通知什么的)傳到DB中,其中難免會分段,分行什么的.可是我們從DB中取出來直接在JSP頁面顯示時出來的卻是從頭到尾的一片文字!!!
解決方法:
首先應(yīng)將在DB中的相關(guān)顯示文字取出來的時候進(jìn)行一個轉(zhuǎn)換,比如說把里面的回車,換行,空格什么的轉(zhuǎn)換成HTML能識別的標(biāo)記.也許以下代碼正是我們需要的:


public class CheckData extends Object
{



/** *//** *//** *//** *//** *//** *//** *//**
* CheckData 構(gòu)造器
*
* @param
* @return

*/


public CheckData()
{}



/** *//** *//** *//** *//** *//** *//** *//**
* 字符串替換,將 source 中的 oldString 全部換成 newString
*
* @param source 源字符串
* @param oldString 老的字符串
* @param newString 新的字符串
* @return 替換后的字符串
*/

public static String Replace(String source, String oldString, String newString)
{
StringBuffer output = new StringBuffer();

int lengthOfSource = source.length(); // 源字符串長度
int lengthOfOld = 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 + lengthOfOld;
}


if (posStart < lengthOfSource)
{
output.append(source.substring(posStart));
}

return output.toString();
}


/** *//** *//** *//**//*
public static String ReplaceIgnoreCase(String source, String oldString, String newString) {
}
*/


/** *//** *//** *//** *//** *//** *//** *//**
* 將字符串格式化成 HTML 代碼輸出
* 只轉(zhuǎn)換特殊字符,適合于 HTML 中的表單區(qū)域
*
* @param str 要格式化的字符串
* @return 格式化后的字符串
*/

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

String html = new String(str);

html = Replace(html, "&", "&");
html = Replace(html, "<", "<");
html = Replace(html, ">", ">");

return html;
}


/** *//** *//** *//** *//** *//** *//** *//**
* 將字符串格式化成 HTML 代碼輸出
* 除普通特殊字符外,還對空格、制表符和換行進(jìn)行轉(zhuǎn)換,
* 以將內(nèi)容格式化輸出,
* 適合于 HTML 中的顯示輸出
*
* @param str 要格式化的字符串
* @return 格式化后的字符串
*/

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

String html = new String(str);

html = toHtmlInput(html);
html = Replace(html, "\r\n", "\n");
html = Replace(html, "\n", "<br>\n");
html = Replace(html, "\t", " ");
html = Replace(html, " ", " ");

return html;
}

}


好啦,現(xiàn)在你可以直接通過類調(diào)用相應(yīng)的方法(比如說toHtml)后,就成了HTML能識別的格式了.如你在DB中的內(nèi)容可能如下:
"lilin and you do it "
也許轉(zhuǎn)換后成了
"lilin and you do it<br> "
接下來也許我們會很自然地想到用JS(innerTHML,document.write()等等來處理)來將其輸出到JSP中.然而結(jié)果卻往往不是我們想要的,原因是你在DB中的數(shù)據(jù)不符合JS的語法,因為在JS中要求所有的輸出語句均在同一行中,否則就會出現(xiàn)"未結(jié)束的字符串常量"的錯誤.而我們轉(zhuǎn)換后的僅僅是把DB中數(shù)據(jù)用HTML標(biāo)識符來替代,比如說若有一行空白,那么很可能對應(yīng)的就是一個"<BR>"符號,但是這個符號依然會占一行...(大概是這個意思)
我在JSP頁面中,直接將它們out出來的(想一下servlet是怎么直接顯示布面內(nèi)容的^_^,雖然我一向?qū)ervlet這樣的行為比較反感)!不管我們轉(zhuǎn)換后的字符串中有多少行,全部把它放到out中就可以了!惟一的缺陷是又要在JSP中多一個"<%=%>"符號.
不知道各位有什么別的好方法沒有?