Domanda

Sono un ragazzo php, ma devo fare qualche piccolo progetto in JSP. Mi chiedo se esiste un equivalente alla funzione htmlentities (di php) in JSP.

È stato utile?

Soluzione

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();
}

Altri suggerimenti

  

stringhe statiche pubbliche stringToHTMLString (string string) {...

La stessa cosa fa l'utilità dalla commons-lang libreria:

org.apache.commons.lang.StringEscapeUtils.escapeHtml

Basta esportarlo in tld personalizzato e otterrai un metodo pratico per jsp.

Suggerisco di usare escapeXml impostato su vero attributo di JSTL direttamente in JSP

<c:out value="${string}" escapeXml="true" />
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top