문자열을 웹 문서에 올바르게 표시되는 문자열로 변환하는 방법이 있습니까? 예를 들어,Java에서 HTML 특수 문자를 이스케이프 처리하는 방법은 무엇입니까?
"<Hello>"
문자열을 웹 문서에 올바르게 표시되는 문자열로 변환하는 방법이 있습니까? 예를 들어,Java에서 HTML 특수 문자를 이스케이프 처리하는 방법은 무엇입니까?
"<Hello>"
StringEscapeUtils
에 문자열
"<Hello>"
을 변경하면이를 위해 정확하게 설계된 기능이 있습니다
일반적으로 "HTML 탈출"라고. XML을 사용하여 접근 할 수는 있지만 표준 라이브러리에서이 작업을 수행하는 것에 대해서는 전혀 알지 못합니다. 그러나이를 수행 할 수있는 타사 라이브러리가 많이 있습니다. org.apache.commons.lang의 StringEscapeUtils에는 escapeHtml
메소드가 있습니다.
public static String stringToHTMLString(String string) {
StringBuffer sb = new StringBuffer(string.length());
// true if last char was blank
boolean lastWasBlankChar = false;
int len = string.length();
char c;
for (int i = 0; i < len; i++)
{
c = string.charAt(i);
if (c == ' ') {
// blank gets extra work,
// this solves the problem you get if you replace all
// blanks with , if you do that you loss
// word breaking
if (lastWasBlankChar) {
lastWasBlankChar = false;
sb.append(" ");
}
else {
lastWasBlankChar = true;
sb.append(' ');
}
}
else {
lastWasBlankChar = false;
//
// HTML Special Chars
if (c == '"')
sb.append(""");
else if (c == '&')
sb.append("&");
else if (c == '<')
sb.append("<");
else if (c == '>')
sb.append(">");
else if (c == '\n')
// Handle Newline
sb.append("<br/>");
else {
int ci = 0xffff & c;
if (ci < 160)
// nothing special only 7 Bit
sb.append(c);
else {
// Not 7 Bit use the unicode system
sb.append("&#");
sb.append(new Integer(ci).toString());
sb.append(';');
}
}
}
}
return sb.toString();
}
유니 코드 보조 문자는 문자열에서 2 개의 문자로 인코딩되며 올바르게 렌더링되지 않습니다. 유니 코드를 지원하려면 문자가 아닌 코드 포인트를 처리해야합니다. – Jakub
안녕하세요, 이건 오래된 q입니다.하지만 궁금한 점이 있습니다. 문자 하나 하나씩 처리하는 대신 String.replaceAll() 메서드가 작동하지 않는 이유는 무엇입니까? –
를 htmlentities 정적 메서드의 컬렉션을 포함하는 오픈 소스 자바 클래스 (를 htmlentities은, unhtmlentities는, ...) HTML의 entitities에 그 반대 특별하고 확장 문자를 변환합니다.
http://www.tecnick.com/public/code/cp_dpage.php?aiocp_dp=htmlentities
이 링크는 더 이상 작동하지 않습니다. 클래스는 http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringEscapeUtils.html에서 찾을 수 있으며 여기에 포함 된 프로젝트는 http : //입니다. commons.apache.org/proper/commons-lang/ – Jakub
@ Jakub Thanks. 게시물을 최신 URL로 업데이트했습니다. – Amber