스프링부트에서 html 페이지로 이동할경우
@Controller를 사용하여 resource/templates에 있는 페이지를 자동으로 이동한다
사용방법
1. 타임리프
타임리프는 static 폴더 안에 매핑되는 html 파일을 찾아 렌더링 해준다
타임리프란, 스프링에서 제공해주는 템플릿 엔진이다
build.gralde에 아래와 같은 코드를 추가한다
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'

2. Controller코드
home.html를 resource/templates 아래 있는지 확인후 있을 경우 return 해준다


*** 주의할점 ***
이 때 @RestController를 사용하면 html 페이지를 return 하지 않는다
@Controller 는 주로 @Web페이지의 컨트롤러에서 사용된다
Web 페이지용 컨트롤러는 JSP나 템플릿 엔진 View로 전환 응답의 HTML을 생성하기 때문에
기본적으로 메소드의 반환 값은 View 전환 대상을 지정할때 사용한다
@RestController 는 Json이나 XML 등을 반환하는 WebAPI용 컨트롤러로 사용한다
이것은 View로 전환하지 않기 때문에 메소드의 값은 응답의 내용이 된다.
필자는 @RestController가 @Controller와 @ResponseBody의 동작을 조합한 어노테이션으로 알고 있었다.
그래서 @RestController가 @Controller의 기능을 갖고 있으니깐
@Controller 대신 @RestController를 사용해도 될 줄 알았는데
@ResponseBody 기능도 있기에 그 응답이 ResponseBody에 담겨 View 템플릿으로 렌더링 할 수없다
참고:https://thalals.tistory.com/221
'Spring > 공부' 카테고리의 다른 글
[Spring] @Component, @Repository, @Service, @Controller (0) | 2024.01.17 |
---|---|
[Spring] 생명주기 ( Life Cycle) (0) | 2024.01.16 |
[Spring] 의존객체 자동 주입 (@Autowired, @Resource, @injec 차이) (0) | 2024.01.15 |
[오류] application.xml cvc-elt.1.a: cannot find the declaration of element 'beans'. (0) | 2024.01.11 |
[오류] pom.xml 오류 cvc-elt.1.a:Cannot find the declaration of element 'project' (0) | 2024.01.11 |