Question

Je suis un gars de PHP, mais je dois faire un petit projet dans JSP. Je me demande s’il existe une fonction équivalente à htmlentities (de php) dans JSP.

Était-ce utile?

La solution

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

Autres conseils

  

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

La même chose s'applique à l'utilitaire de la bibliothèque commons-lang :

org.apache.commons.lang.StringEscapeUtils.escapeHtml

Exportez-le simplement dans un fichier tld personnalisé. Vous obtiendrez une méthode pratique pour jsp.

Je suggère d'utiliser escapeXml défini sur l'attribut true de JSTL directement dans JSP

<c:out value="${string}" escapeXml="true" />
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top