본문 바로가기

Back End/Spring

[Spring] Controller 에서 HTML텍스트를 HTML페이지로 리턴하기.

반응형

■ 목표

- Spring 컨트롤러에서 HTML텍스트를 브라우저에서 바로 렌더링되도록 리턴한다.

(보통 jsp나 html파일 경로를 리턴하는데 HTML문서의 본문 텍스트를 리턴하는 방법이다.)

이런 방법을 쓸일이 없을것만 같은데 일하다보니 생긴다...

 

샘플로 사용할 HTML은 아래와 같다.

<!doctype html>
<html> 
    <head>
        <title>Example: 2-1</title>
    </head>
    <body>
        <h1>example 2-1</h1>
        <h2>html example</h2>
        
        <p>hello world</p>
        <p>hello
            world
        </p>
        <p>hello<br>world</p>
        <pre>
            hello world
            hello
                world
        </pre>
        <pre>
            <h2>hello
                    world
            </h2>
        </pre>
    </body>
</html>

 

■ 소스코드

방법은 간단하다. 

Controller에서 response를 인자로 받아, 해당 response에 직접 HTML 본문을 출력하면 된다.

 

단 보안적인 측면은 무시하고 테스트로 개발하였다.

보안이 필요한 페이지라면 헤더 등을 사용해 인증 관련 코드를 추가한다.

또한 사용자가 입력한 HTML을 리턴하게 된다면 HTML내부에 JS가 들어갈 수 있어 위험할 수 있다고 본다.

@GetMapping("/html")
    public void html(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        response.getWriter().print("<!doctype html>\n" +
                "<html> \n" +
                "    <head>\n" +
                "        <title>Example: 2-1</title>\n" +
                "    </head>\n" +
                "    <body>\n" +
                "        <h1>example 2-1</h1>\n" +
                "        <h2>html example</h2>\n" +
                "        \n" +
                "        <p>hello world</p>\n" +
                "        <p>hello\n" +
                "            world\n" +
                "        </p>\n" +
                "        <p>hello<br>world</p>\n" +
                "        <pre>\n" +
                "            hello world\n" +
                "            hello\n" +
                "                world\n" +
                "        </pre>\n" +
                "        <pre>\n" +
                "            <h2>hello\n" +
                "                    world\n" +
                "            </h2>\n" +
                "        </pre>\n" +
                "    </body>\n" +
                "</html>");
    }

 

단 아래처럼 response의 contentType과 encodeng을 정해줘야 한다.

정해주지 않으면 특정 브라우저(사파리) 에서 HTML인지 구분을 하지 못해 텍스트로 출력된다.

크롬, 엣지에서는 자동으로 HTML이라고 판단해 그려주는 것으로 보인다.

 

PostMan으로 테스트한 결과는 아래와 같다.

 

 

소스에서 설정한 대로 ContentType 및 인코딩이 설정되어 있다.

 

당연히 브라우저에서도 원하는 대로 잘 보인다.

반응형