Mustache 의 파생인 handlebarsjs 의 자바 구현물인 handlebars.java 와 스프링 mvc 연동 


JDK 7 이상 필요


pom.xml

<properties>
   <java-version>1.8</java-version>
   <org.springframework-version>4.2.9.RELEASE</org.springframework-version>
   <org.slf4j-version>1.6.6</org.slf4j-version>
   <handlebars-version>4.0.6</handlebars-version>
   <jackson.version>2.4.4</jackson.version>
</properties>


<dependencies>
	...
	<dependency>
	   <groupId>com.github.jknack</groupId>
	   <artifactId>handlebars</artifactId>
	   <version>${handlebars-version}</version>
	</dependency>
	<dependency>
	   <groupId>com.github.jknack</groupId>
	   <artifactId>handlebars-jackson2</artifactId>
	   <version>${handlebars-version}</version>
	</dependency>
	<dependency>
	   <groupId>com.github.jknack</groupId>
	   <artifactId>handlebars-springmvc</artifactId>
	   <version>${handlebars-version}</version>
	</dependency>
</dependencies>
XML


spring mvc view resolver 설정

  • webapp/resources/handlebars 폴더 생성
  • spring 의 컨텍스트 설정에 .hbs 확장자 view resolver 에 추가.

servlet-context.xml

<!-- handle bar: jdk 7 이상에서만 지원함 -->
<beans:bean class="com.github.jknack.handlebars.springmvc.HandlebarsViewResolver">
   <beans:property name="prefix" value="/WEB-INF/handlebars/"/>
   <beans:property name="suffix" value=".hbs"/>
</beans:bean>
XML


테스트

Controller 추가

package com.example.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public ModelAndView  hello(@RequestParam(value = "name", required = false) String  name) {
        ModelAndView m = new ModelAndView("hello");

        m.addObject("name",  name);
        m.addObject("message", "Hello world!");

        return m;
    }
}
JAVA


View 추가

webapp/resources/handlebars/hello.hbs

webapp/resources/handlebars/hello.hbs

<!DOCTYPE html>
<html>

<head>
  <title>handlebars test</title>
</head>

<body>
    <h1> handlebars test</h1>

    Hello "{{ this.name }}"<br/>
    message: {{this.message}}!<br/>
    class: "{{ this }}"

</body>

</html>
XML


Ref