猿问

用Java转义HTML的推荐方法

用Java转义HTML的推荐方法

有没有推荐的逃跑方法<>"&在普通Java代码中输出HTML时的字符?(除手动执行以下操作外)。

String source = "The less than sign (<) and ampersand (&) must be escaped before using them in HTML";
String escaped = source.replace("<", "&lt;").replace("&", "&amp;"); // ...


函数式编程
浏览 1659回答 3
3回答

慕莱坞森

StringEscapeUtils从…阿帕奇公域朗:import&nbsp;static&nbsp;org.apache.commons.lang.StringEscapeUtils.escapeHtml; //&nbsp;...String&nbsp;source&nbsp;=&nbsp;"The&nbsp;less&nbsp;than&nbsp;sign&nbsp;(<)&nbsp;and&nbsp;ampersand&nbsp;(&)&nbsp;must&nbsp;be&nbsp;escaped&nbsp;before&nbsp;using&nbsp;them&nbsp;in&nbsp;HTML";String&nbsp;escaped&nbsp;=&nbsp;escapeHtml(source);为第3版:import&nbsp;static&nbsp;org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;//&nbsp;...String&nbsp;escaped&nbsp;=&nbsp;escapeHtml4(source);

沧海一幻觉

ApacheCommons的另一种选择:使用春天氏HtmlUtils.htmlEscape(String input)方法。
随时随地看视频慕课网APP
我要回答