小编典典

在Java中转义HTML的推荐方法

java

有没有逃脱推荐的方式<,>"&字符时输出HTML中普通的Java代码?(也就是说,除了手动执行以下操作之外)。

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

阅读 446

收藏
2020-02-28

共1个答案

小编典典

来自Apache Commons LangStringEscapeUtils

import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
// ...
String source = "The less than sign (<) and ampersand (&) must be escaped before using them in HTML";
String escaped = escapeHtml(source);

对于版本3:

import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;
// ...
String escaped = escapeHtml4(source);
2020-02-28