JSP中的htmlentities等价?

时间:2008-11-30 03:11:33

标签: java jsp html-entities

我是一个php人,但我必须在JSP中做一些小项目。 我想知道在JSP中是否有相当于htmlentities函数(php)。

3 个答案:

答案 0 :(得分:8)

  

public static String stringToHTMLString(String string){...

同样的事情来自commons-lang库的实用程序:

org.apache.commons.lang.StringEscapeUtils.escapeHtml

只需将其导出到自定义tld中 - 您将获得一个方便的jsp方法。

答案 1 :(得分:3)

public static String stringToHTMLString(String string) {
    StringBuffer sb = new StringBuffer(string.length());
    // true if last char was blank
    boolean lastWasBlankChar = false;
    int len = string.length();
    char c;

    for (int i = 0; i < len; i++)
        {
        c = string.charAt(i);
        if (c == ' ') {
            // blank gets extra work,
            // this solves the problem you get if you replace all
            // blanks with &nbsp;, if you do that you loss 
            // word breaking
            if (lastWasBlankChar) {
                lastWasBlankChar = false;
                sb.append("&nbsp;");
                }
            else {
                lastWasBlankChar = true;
                sb.append(' ');
                }
            }
        else {
            lastWasBlankChar = false;
            //
            // HTML Special Chars
            if (c == '"')
                sb.append("&quot;");
            else if (c == '&')
                sb.append("&amp;");
            else if (c == '<')
                sb.append("&lt;");
            else if (c == '>')
                sb.append("&gt;");
            else if (c == '\n')
                // Handle Newline
                sb.append("&lt;br/&gt;");
            else {
                int ci = 0xffff & c;
                if (ci < 160 )
                    // nothing special only 7 Bit
                    sb.append(c);
                else {
                    // Not 7 Bit use the unicode system
                    sb.append("&#");
                    sb.append(new Integer(ci).toString());
                    sb.append(';');
                    }
                }
            }
        }
    return sb.toString();
}

答案 2 :(得分:1)

我建议直接在JSP

中使用escapeXml set设置为JSTL的true属性
<c:out value="${string}" escapeXml="true" />