我想在启用 HTML 的 JLabel 中显示不安全的文本(来自用户),例如 <html><p>Unsafe user input here</p></html>
。我应该怎样做才能转义用户提供的字符串数据以适应我的启用 HTML 的环境而不造成任何麻烦?
最佳答案
基于Which characters need to be escaped on HTML?我建议使用以下代码:
public class SimpleEscaping {
private static final Pattern[] patterns = new Pattern[]{
Pattern.compile("&"),
Pattern.compile("<"),
Pattern.compile(">")
};
private static final String[] replacements = {
"&",
"<",
">"
};
public static String escapeHTML(String input) {
for (int i = 0; i < patterns.length; i++)
input = patterns[i].matcher(input).replaceAll(replacements[i]);
return input;
}
}
关于java - JLabel 的转义 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16252829/