🗃️ 내가 다시 볼 것

템플릿 엔진 렌더링이 안되는 문제 (@RestController와 @Controller)

전호영 2024. 10. 7. 00:15

문제상황

개발자 유미님의 SpringSecurity 강의를 듣던 중 문제 발생.

 

컨트롤러

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @GetMapping("/login")
    public String loginP() {
        return "login";
    }
}

 

템플릿 엔진(mustache)

<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
login page
<hr>
<form action="/loginProc" method="post" name="loginForm">
    <input id="username" type="text" name="username" placeholder="id"/>
    <input id="password" type="password" name="password" placeholder="password"/>
    <input type="submit" value="login"/>
</form>
</body>
</html>

 

/login으로 접속을 하면 

login 만 출력이 된다.


문제해결

@RestController -> @Controller로 변경하면 제대로 mustache가 렌더링 된다.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class LoginController {

    @GetMapping("/login")
    public String loginP() {
        return "login";
    }
}

 

 

 

 


문제원인

@RestController 는 @Controller + @ResponseBody 로 응답이 Http응답으로 직렬화된다.

그래서 템플릿 엔진이 렌더링되지 않고 login 이 그대로 반환됐던 것이다.

 

 

 


참고

 

RestController (Spring Framework 6.1.13 API)

The value may indicate a suggestion for a logical component name, to be turned into a Spring bean in case of an autodetected component.

docs.spring.io

 

 

 

@ResponseBody :: Spring Framework

@ResponseBody is also supported at the class level, in which case it is inherited by all controller methods. This is the effect of @RestController, which is nothing more than a meta-annotation marked with @Controller and @ResponseBody. @ResponseBody suppor

docs.spring.io

 

 

Reactive Core :: Spring Framework

The org.springframework.web.server package builds on the HttpHandler contract to provide a general-purpose web API for processing requests through a chain of multiple WebExceptionHandler, multiple WebFilter, and a single WebHandler component. The chain can

docs.spring.io

(Codecs 파트 참고)