3

I would like to display an unsafe text (from user) in a HTML-enabled JLabel, for example <html><p>Unsafe user input here</p></html>. What should I do to escape the user supplied string data to fit into my HTML enabled environment without causing any troubles?

Notinlist
  • 16,144
  • 10
  • 57
  • 99
  • http://stackoverflow.com/questions/3584263/how-to-disable-the-automatic-html-support-of-jlabel – ditkin Apr 27 '13 at 13:58
  • Answers uses nonstandard com.sun.* components and-or ends up using JList (which is not an answer for me). – Notinlist Apr 27 '13 at 14:05
  • Do you mean something like [`StringEscapeUtils`](http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html#escapeHtml%28java.lang.String%29)? – Duncan Jones Apr 27 '13 at 14:53
  • 1
    @DuncanJones More or less. It is a third party lib. Bringing in a lib just to do that simple thing is not pleasant. Can standard Java API help me? If they accept (even expect) HTML inputs then they should provide basic HTML utilities. At least escaping IMHO. I could write my own escaping (not that difficult - 5 lines), but that would not be future proof. – Notinlist Apr 27 '13 at 18:29

1 Answers1

0

Based on Which characters need to be escaped on HTML? I propose the following code:

public class SimpleEscaping {

    private static final Pattern[] patterns = new Pattern[]{
        Pattern.compile("&"),
        Pattern.compile("<"),
        Pattern.compile(">")
    };
    private static final String[] replacements = {
        "&amp;",
        "&lt;",
        "&gt;"
    };

    public static String escapeHTML(String input) {
        for (int i = 0; i < patterns.length; i++)
            input = patterns[i].matcher(input).replaceAll(replacements[i]);
        return input;
    }
}
Community
  • 1
  • 1
Panayotis
  • 1,792
  • 23
  • 32