VSCode - Spring Boot 프로젝트에서 MVC 패턴으로 View 호출

GARY·2022년 4월 3일
0

이전 포스팅에서 만든 Spring Boot 프로젝트에서 MVC 패턴으로 View 화면을 호출해보자.

MVC 패턴 사용하기 위한 설정

1> build.gradle 파일에 라이브러리 추가

-- implementation 'org.apache.tomcat.embed:tomcat-embed-jasper' 추가

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	developmentOnly 'org.springframework.boot:spring-boot-devtools'
	providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'

	implementation 'org.apache.tomcat.embed:tomcat-embed-jasper'
}

-- View 화면에 사용할 템플릿 엔진을 위한 라이브러리
-- Spring Boot 용 템플릿은 jsp뿐 아니라 Thymeleaf, Freemarker, Groovy 등도 지원 (Spring Boot 에선 Thymeleaf나 Freemarker 추천)

2> application.properties 파일에 url 주소에 대한 prefix와 suffix 설정

spring.mvc.view.prefix=/WEB-INF/template/
spring.mvc.view.suffix=.jsp

3> Controller 수정

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloController {
    
    @RequestMapping("/")
    public String index(
        @RequestParam(name = "name", required = false, defaultValue = "World")
        String name, 
        Model model
    ) {
        model.addAttribute("name", name);
        return "index";
    }
}

4> prefix 경로에 index.jsp 파일 생성

5> 간단하게 index.jsp 작성

<!DOCTYPE html>
<html>
    <head>
        <title>Hello, ${name}!</title>
    </head>
    <body>
        <div>Hello, ${name}!</div>
    </body>
</html>

6> 프로젝트 Run

profile
개발하는 개린이 개리

0개의 댓글