Post View

Java에서 HTML 문자 escape 하기

"페이지 벗어나는 경우 팝업 출력하기" 글을 작성하고 나서 오타를 발견해 수정을 하는데, HTML이 틀어져 있는 것을 확인했습니다.

증상을 보니 <code> 태그 내부에 적어두었던 코드 부분이 HTML로 나타나면서 글이 아닌 HTML Elment로 나타나는 현상이었습니다.
처음 글에 적은 내용은 "&lt;html&gt;"처럼 HTML이 escape 된 형태였는데, 다시 글을 불러오는 경우 아무래도 ckeditor에서 unescape를 하는 듯 합니다.

글을 작성할 때나 글을 보는 화면에서는 문제가 없으니 글을 수정하기 위해 DB에서 불러오는 경우에만 서버쪽에서 escape를 한번 더 하도록 처리하였습니다.

/**
* 관리자가 작성했던 포스트를 수정한다.
*
* @param postNo
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value = "/modify/{postNo}", method = RequestMethod.GET)
public String modify(@PathVariable int postNo, Model model) throws Exception {
    Post post = postService.get(postNo, "Y");
    List<Category> categories = categoryService.getList();
    
    String htmlEscapeContent = StringEscapeUtils.escapeHtml4(post.getPostContent());
    post.setPostContent(htmlEscapeContent);
    
    model.addAttribute("post", post);
    model.addAttribute("categories", categories);
    model.addAttribute("formAction", "modifyUpdate");
    model.addAttribute("formSubmit", "수정");
    
    template.setTitle(post.getPostSubject() + " : Post Modify &dash; Kurien's Blog");
    template.getCss().add("<link rel=\"stylesheet\" href=\"/css/module/post.css\">");
    
    return "admin/post/admin/write";
} 

색상이 진하게 처리된 부분을 보면, StringEscapeUtils 클래스의 escapeHtml4 메서드를 사용했습니다.
postContent는 제 포스팅의 본문에 해당하는 부분인데요.
DB에서 가져온 포스팅의 본문에서 HTML을 escape 하여 다시 postContent에 추가하여 처리하였습니다.

그렇다면 StringEscapeUtils는 어떤 클래스일까요?
http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringEscapeUtils.html
apache commons에서 제공하는 문서를 보니, commons-lang 라이브러리에서 제공하는 클래스는 더 이상 사용되지 않는다고 합니다.
대신 https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html
위 경로에서 제공하는 StringEscapeUtils 클래스를 사용하라고 하네요.

제 경우에는 commons-lang 라이브러리는 기본적으로 추가되어있었지만, commons-text 라이브러리는 추가를 해줘야 했습니다.
commons-text 라이브러리는 https://mvnrepository.com/artifact/org.apache.commons/commons-text에서 쉽게 찾을 수 있었습니다.
제가 사용한 버전은 1.8이며, pom.xml에 Maven dependency를 추가했습니다.

수정이 완료되었으니 다시한번 글수정 화면을 확인 해볼까요?

정상적으로 수정이 완료되었습니다.

HTML에서는 태그 형태의 문자를 태그가 아닌 문자로 인식시키기 위한 HTML Entity가 있는데,
오늘 처리했던 escape는 HTML 태그를 HTML Entity로 변경해주는 역할을 합니다.
반대로 unescape는 HTML Entity를 HTML 태그로 변환시키는 역할을 하구요.

아래의 URL로 접속하시면 html에서 사용하는 Entity를 확인해보실 수 있습니다.
https://dev.w3.org/html5/html-author/charref

외우기보단 이런 것이 있고 이런 이유로 사용한다는 것을 알고 있다면 언제든지 찾아볼 수 있습니다.
한번쯤은 봐두시기를 추천드립니다.

Comments