티스토리 뷰

언제부턴가 JSP를 사용하면 노후화된 시스템이라는 딱지가 붙게 되었다. 10년을 넘게 JSP를 사용하며 영원할것 같았던 이 기술은 어느샌가 고인물의 영역이 되어가고 있는것 같다. JSP는 Spring 진영에서 정식 template engine으로 지원하지 않고 JavaEE에 종속적인 한계가 명확한것이 사람들이 점차 안쓰는데 가장 큰 이유가 아닐까 싶다. 하지만 여전히 JSP의 성능은 뛰어나다. 

참고 : https://jangcool.tistory.com/entry/Java-Template-%EC%84%B1%EB%8A%A5-%EB%B9%84%EA%B5%90

Java template engine을 비교한 자료인데 성능은 JSP+JSTL이 최고고 그다음이 freemarker이다. 그래서 성능의 차이는 최소로 하며 현재 트랜드에 맞는 구조로 가기 위해서 freemarker로 프로젝트를 진행하기로 하였다. 

이번에는 프로젝트를 만들고 HelloWorld만 찍어보는 프로젝트를 하나 만들어 보자. 


1. Freemarker 프로젝트 생성

spring starter project 생성

STS에서 Create new Spring Starter Project를 클릭하여 새로운 프로젝트를 하나 만든다. 

 

spring starter project 생성

적당한 프로젝트 이름을 지어주고 Next, 그리고 dependency로는 Apache Freemarker와 Spring Web을 추가한다. 새로운 프로젝트 생성이 아니라면 다음과 같은 dependency를 프로젝트에 추가를 해주자. 

pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

springboot + freemarker project 생성

프로젝트를 생성하면 위와 같이 resources 밑에 static 폴더와 template 폴더가 생성이 된다. static은 정적 resource (css, js, image ..) 를 넣는 곳이고 templates은 freemarker의 view 파일과 같은 resource를 넣는 곳이다. 새로운 프로젝트가 아니라면 이런 폴더를 만들어주자.

이렇게 하면 freemarker를 사용하는 프로젝트 생성은 모두 끝이 났다. 

 

2. Freemarker 기본 세팅 

application.properties

spring.freemarker.template-loader-path=classpath:/templates 
spring.freemarker.suffix=.ftl

springboot가 freemarker를 사용하겠다는 설정을 application.properties (or application.yml) 에 해준다. 

 

3. Freemarker 파일 생성 및 실행

Freemarker 파일 생성

프로젝트에 위와 같이 Controller 하나, ftl 하나 생성을 한다. 

helloWorld.ftl 생성

<!DOCTYPE html>
<html>
    <head>
        <title>first page</title>
    </head>
    <body>
        <h2>hello freemarker world ${name}</h2>
    </body>
</html>

위에서 언급한대로 resources/templates 하위에 ftl 파일을 생성한다. hello freemarker world 라는 문구를 찍어준다. 

ftl 파일을 열었을때 검정색으로 나오는것은 일반 text 파일로 인식해서 그렇다. jsp 처럼 보이게 하려면 여기를 참고하도록 하자. 

 

HelloWorldController.java 생성

@Controller
public class HelloWorldController {
	
    @GetMapping("/helloWorld/{name}")
    public String test(Model model, @PathVariable("name") String name) {
        model.addAttribute("name", name);
        return "helloWorld";
    }
}

helloWorld라는 return을 주게 되면 application.properties에서 설정한대로 classpath:/templates/helloWorld.ftl 파일을 찾아가게 되어 위에서 작성한 helloWorld.ftl 의 내용을 출력하게 된다.

 

결과

localhost:8080/helloWorld/홍길동 입력시 

freemarker helloworld

이렇게 helloWorld.ftl 의 내용을 정상적으로 출력하는것을 확인할 수 있다. 

 

끝!

댓글
최근에 올라온 글
최근에 달린 댓글
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31