๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๊ฐœ๋ฐœ์ด์•ผ๊ธฐ

Spring Boot ์—๋Ÿฌ ํ™”๋ฉด ์ถœ๋ ฅ (Thymeleaf)

๋ฐ˜์‘ํ˜•

์Šคํ”„๋ง ๋ถ€ํŠธ (Spring Boot)์˜ ์—๋ŸฌํŽ˜์ด์ง€๊ฐ€ ์•„๋‹Œ, ๋ณ„๋„์˜ ์—๋Ÿฌ ํ™”๋ฉด์„ ์ถœ๋ ฅํ•˜๊ธฐ ์œ„ํ•ด ์ž‘์—… ํ–ˆ๋‹ค.

 

ํ…œํ”Œ๋ฆฟ์—”์ง„์€ tymeleaf๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ๋Š”๋ฐ,

 

์‚ฌ์‹ค, 404๋‚˜ 500 ๋“ฑ๋“ฑ ๊ฐ http status ์ฝ”๋“œ์— ๋งž๊ฒŒ ํ…œํ”Œ๋ฆฟ ์—”์ง„๋งŒ ์ถ”๊ฐ€ํ•˜๋ฉด ๋˜์ง€๋งŒ,

 

๋ชจ๋“  ์—๋Ÿฌ ํ™”๋ฉด์„ ๋™์ผํ•˜๊ฒŒ ์ถœ๋ ฅ์‹œํ‚ค๊ธฐ ์œ„ํ•ด์„œ Error Controller๋ฅผ ์ƒ์„ฑํ•ด ์ฒ˜๋ฆฌํ•ด์ฃผ๊ธฐ๋กœ ํ–ˆ๋‹ค.

 

๊ธฐ๋ณธ์ ์œผ๋กœ http status๊ฐ€ 200์ด ์•„๋‹Œ ๊ฒฝ์šฐ ์•„๋ž˜์™€ ๊ฐ™์ด ํ™”์ดํŠธ๋ผ๋ฒจ ์—๋Ÿฌ ํ™”๋ฉด์ด ์ถœ๋ ฅ๋œ๋‹ค

 

 

๋งŒ์•ฝ ์ฝ”๋“œ๋ณ„๋กœ ์—๋Ÿฌํ™”๋ฉด์„ ๋‹ค๋ฅด๊ฒŒ ์ถœ๋ ฅํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด, ์•„๋ž˜์™€ ๊ฐ™์ด ํ…œํ”Œ๋ฆฟ ํด๋”์•„๋ž˜์— status code์— ๋งž๋Š” htmlํŒŒ์ผ์„ ์ƒ์„ฑํ•ด์„œ ๋„ฃ์–ด์ฃผ๋ฉด ๋จ

- resources > templates > error

 

๊ทผ๋ฐ ๋‚˜๋Š”, http status code๊ฐ€ 200์ด ์•„๋‹Œ ๊ฒฝ์šฐ ๋ชจ๋‘ ๋‹ค ๊ฐ™์€ ์—๋Ÿฌ ํ™”๋ฉด์„ ์ถœ๋ ฅํ•˜๊ธฐ ์œ„ํ•ด ๋ณ„๋„์˜ ์ปจํŠธ๋กค๋Ÿฌ๋ฅผ ์ƒ์„ฑํ•˜๊ณ  ์ œ์–ด ํ•  ์˜ˆ์ •.

 

ํŒจํ‚ค์ง€ ์•ˆ์—, ์ปจํŠธ๋กค๋Ÿฌ ํŒŒ์ผ์„ ์ƒ์„ฑ

@Controller
public class CommonErrorController implements ErrorController {
    @RequestMapping(value = "/error")
    public String handleError(HttpServletRequest request) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        if(status != null)
        {
            return "error/err";
        }
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}

 

 

์œ„์™€ ๊ฐ™์ด ์ปจํŠธ๋กค๋Ÿฌ ์ƒ์„ฑ, templates/error ํด๋”๋‚ด err.html ํŒŒ์ผ ์ƒ์„ฑ

 

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Common Error</title>
    <link rel="stylesheet" th:href="@{/css/style.css}">
    </link>
</head>
<body>
<div class="errorPage">
    <span class="errorHead">errrrrrrrr</span><br />
</div>
</body>
</html>

์œ„์™€ ๊ฐ™์ด ์ƒ์„ฑํ•˜๋ฉด, http status code๊ฐ€ 200์ด ์•„๋‹Œ ๊ฒฝ์šฐ ๋ชจ๋‘ ๋™์ผํ•œ error ํ™”๋ฉด์„ ์ถœ๋ ฅํ•˜๊ฒŒ ํ•œ๋‹ค.

 

 

 

์ฐธ๊ณ 

tymeleaf ํ…œํ”Œ๋ฆฟ์—์„œ <head></head>์•ˆ์— css ํŒŒ์ผ import ํ•  ๋•Œ ์ •์  ํŒŒ์ผ ์ž„ํฌํŠธ ํ•˜๋Š” ํŒŒ์ผ ์œ„์น˜๋ฅผ ์ฐพ์•„ ํ—ค๋งธ์—ˆ์—ˆ๋Š”๋ฐ,

 

resources > static

static > css ํด๋”์— ํ•ด๋‹น ์Šคํƒ€์ผ์‹œํŠธ๋ฅผ ๋„ฃ์–ด์ฃผ๋ฉด ๋œ๋‹ค

  > js ๋˜๋Š” ๊ธฐํƒ€ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋„ ํ•ด๋‹น ํด๋”์— ๋„ฃ์–ด์ฃผ๊ณ  ์ž„ํฌํŠธ ํ•˜๋ฉด ๋จ