특별한 일상

[JAVA] HTML, MVC, Servlet 환경에서 특수문자 치환(  < > & ...) 본문

IT•개발 끄적/Java

[JAVA] HTML, MVC, Servlet 환경에서 특수문자 치환(  < > & ...)

소다맛사탕 2021. 6. 9. 21:45
반응형

안녕하세요. 소다맛사탕 입니다. 

오늘은 Servlet 이나 HTML, 그리고 GET, POST 형식을 이용해 URL 주소값을 전달할 때..

대부분 자바 서버단으로 이동하는 값은 String 형태로 보내지게 되는데,

여기서 기호가 자동으로 특수문자 처리가 되어버리는 것을 확인할 수 있습니다.

 

예를 들면...

 

jsp에서 url 주소를 html 태그 값에 담아서 보내게 될 경우..

https://develop-sense.tistory.com?main=123&type=234&query=<asdf>

자바 환경에서는

https://develop-sense.tistory.com?main=123&amp;type=234&amp;query=&lt;asdf&gt; 

 

특수문자로 치환된 형태로 보내질 때가 있다는 겁니다.

(HTML, JSP 화면에서 meta가 UTF-8 또는 EUC-KR 인데, 자바 서버단은 반대인 경우도 해당.

말 그대로 인코딩이 안되어 있는 화면에서 주로 발생)

 

이럴 경우 replace나 replaceAll을 사용하여도 좋지만,

저는 아파치에서 제공하는 StringEscapeUtils 클래스를 사용합니다.

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringEscapeUtils.html

 

StringEscapeUtils (Apache Commons Lang 3.12.0 API)

Unescapes any Java literals found in the String. For example, it will turn a sequence of '\' and 'n' into a newline character, unless the '\' is preceded by another '\'.

commons.apache.org

※ 기본적으로 WAS가 Apache tomcat으로 설정을 하셔야 사용할 수 있습니다.

 

import org.apache.commons.lang3.StringEscapeUtils;

해당 클래스를 사용할 수 있게 import 시켜야 합니다.

 

사용법은 간단합니다.

// url이 들어온다.
// HTML 4.0 지원. 실제 유니코드 문자가 포함된 문자열로..
String urlReplace = StringEscapeUtils.unescapeHtml4(url);
// HTML 3.0. 실제 유니코드 문자가 포함된 문자열로..
String urlReplace2 = StringEscapeUtils.unescapeHtml3(url);

자바 서버단으로 전달된 String 값을 위와 같이 사용하면 실제 유니코드 문자가 포함된 상태로 값이 나옵니다.

 

 

package com.blogtest;

import org.apache.commons.lang3.StringEscapeUtils;

public class UrlReplaceStringEscapeUtils {

	public static void main(String[] args) {
		String url = "https://&amp;<&nbsp;&amp;>&amp;";
		
		String urlReplace = StringEscapeUtils.unescapeHtml4(url);
		String urlReplace2 = StringEscapeUtils.unescapeHtml3(url);
		System.out.println(urlReplace);
		System.out.println(urlReplace2);
		
		String url2 = "https://&&&<>";
		
		String urlReplace3 = StringEscapeUtils.escapeHtml4(url2);
		String urlReplace4 = StringEscapeUtils.escapeHtml3(url2);
		System.out.println(urlReplace3);
		System.out.println(urlReplace4);
	}

}

---- 결과 ----

https://&< &>&
https://&< &>&
https://&amp;&amp; &amp;&lt;&gt;
https://&amp;&amp; &amp;&lt;&gt;

 

Comments