[java] Java에서 HTML을 이스케이프 처리하는 데 권장되는 방법

탈출 할 수있는 권장 방법이 <, >, "&일반 자바 코드의 문자 출력 HTML? (수동으로 다음을 수행하는 것 외에).

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



답변

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


답변

Apache Commons의 대안 : SpringHtmlUtils.htmlEscape(String input)방법을 사용하십시오 .


답변

좋은 짧은 방법 :

public static String escapeHTML(String s) {
    StringBuilder out = new StringBuilder(Math.max(16, s.length()));
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c > 127 || c == '"' || c == '\'' || c == '<' || c == '>' || c == '&') {
            out.append("&#");
            out.append((int) c);
            out.append(';');
        } else {
            out.append(c);
        }
    }
    return out.toString();
}

에 기초 https://stackoverflow.com/a/8838023/1199155 (앰프가 누락되었습니다)를 합니다. http://www.w3.org/TR/html4/sgml/entities.html 에 따르면 if 절에서 확인 된 4 개의 문자는 128 미만의 유일한 문자입니다 .


답변

최신 버전의 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");


답변

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


답변

Android (API 16 이상)에서 다음을 수행 할 수 있습니다.

Html.escapeHtml(textToScape);

또는 더 낮은 API :

TextUtils.htmlEncode(textToScape);


답변

이것을 조심하십시오. HTML 문서에는 여러 가지 ‘컨텍스트’가 있습니다. 요소 내부, 인용 된 속성 값, 인용되지 않은 속성 값, URL 속성, 자바 스크립트, CSS 등 … 각각에 대해 다른 인코딩 방법을 사용해야합니다. XSS (Cross-Site Scripting)를 방지합니다. 이러한 각 상황에 대한 자세한 내용 은 OWASP XSS 예방 요령 시트 를 확인하십시오 . OWASP ESAPI 라이브러리 ( https://github.com/ESAPI/esapi-java-legacy) 에서 이러한 각 컨텍스트에 대한 이스케이프 메소드를 찾을 수 있습니다 .