在Java中转义HTML的推荐方法

Java HTML

LGil

2020-04-03

有没有逃脱推荐的方式<>"&字符时输出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;"); // ...

第4001篇《在Java中转义HTML的推荐方法》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

8个回答
宝儿理查德 2020.04.03

出于某些目的,HtmlUtils

import org.springframework.web.util.HtmlUtils;
[...]
HtmlUtils.htmlEscapeDecimal("&"); //gives &#38;
HtmlUtils.htmlEscape("&"); //gives &amp;
Mandy村村 2020.04.03

org.apache.commons.lang3.StringEscapeUtils现在已弃用。您现在必须使用org.apache.commons.text.StringEscapeUtils

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-text</artifactId>
        <version>${commons.text.version}</version>
    </dependency>
GilPro 2020.04.03

请注意这一点。HTML文档中有许多不同的“上下文”:在元素内,带引号的属性值,未带引号的属性值,URL属性,javascript,CSS等...对于每种情况,您都需要使用不同的编码方法这些可以防止跨站点脚本(XSS)。检查在这三个方面的细节OWASP XSS预防小抄- https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet您可以在OWASP ESAPI库(https://github.com/ESAPI/esapi-java-legacy)中找到每种上下文的转义方法

樱小胖Mandy 2020.04.03

对于使用Google Guava的用户:

import com.google.common.html.HtmlEscapers;
[...]
String source = "The less than sign (<) and ampersand (&) must be escaped before using them in HTML";
String escaped = HtmlEscapers.htmlEscaper().escape(source);
宝儿 2020.04.03

有一个Apache Commons Lang库的较新版本,它使用了不同的包名称(org.apache.commons.lang3)。StringEscapeUtils现在有逃避不同类型的文档不同的静态方法(http://commons.apache.org/proper/commons-lang/javadocs/api-3.0/index.html)。因此,要转义HTML 4.0版字符串:

import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;

String output = escapeHtml4("The less than sign (<) and ampersand (&) must be escaped before using them in HTML");
Stafan小哥 2020.04.03

在Android(API 16或更高版本)上,您可以:

Html.escapeHtml(textToScape);

或针对较低的API:

TextUtils.htmlEncode(textToScape);
JinJin 2020.04.03

Apache Commons的替代方法:使用SpringHtmlUtils.htmlEscape(String input)方法。

西里神奇 2020.04.03

来自Apache Commons Lang的StringEscapeUtils

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android