본문 바로가기

Development/JSP

html entity escape/unescape (encode/decode)

escape(encode) : 

특수문자를 그대로 출력되게 하기 위해 대체문자를 적용함.

즉, 사용자에게 <html> 문자를 보여주고 싶은데 <html> 그대로 출력하면 웹페이지 에서는 html 태그로 인식해서 사용자에게 

제대로 보여지지 않는다. &lthtml&gt 이렇게 변환되어야 (escape 되어야 , encode 되어야) <html> 문자가 웹페이지에 

그대로 출력된다.


unescape(decode) : 

escape/encode 된 대체문자를 원래 문자로 되돌려 놓는것

즉, 사용자에게 태그자체를 보여주기 위한 목적이 아니라, 태그의 목적/기능을 사용하기 위해서


/*
아래예제는 서버에서 escape된 태그 문자열이 왔을때 unescape 시키는 방법이다
당연히 그 목적은 html 태그를 보여주기 위한것이 아니라 그 목적/기능을 사용하기 위함이다.
*/
// 필요한 library import
<%@ page import="org.apache.commons.lang.StringEscapeUtils" %>

<%
String json = request.getParameter("json");
String unescapeJson = StringEscapeUtils.unescapeHtml(json);    // html entity 를 unescape 한다.
unescapeJson = StringEscapeUtils.unescapeXml(unescapeJson); // xml entity 를 unescape 한다.
out.println(unescapeJson);
%>