3.3 springboot整合freemarker

2017-06-11 01:40:29 17,541 2

SpringBoot官方不建议在Springboot项目中使用JSP这样的技术,取而代之的是freemarker、velocity这样的模板引擎。本节讲解Springboot与Freemaker的整合。

1、pom.xml

 <parent>
	<artifactId>spring-boot-starter-parent</artifactId>
	<groupId>org.springframework.boot</groupId>
		<version>1.3.1.RELEASE</version>
	<relativePath />
</parent>
 <dependencies>
 ...
 <dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
 <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-freemarker</artifactId>
 </dependency>
 ...
 </dependencies>

2、配置

如果你使用的是application.yml,那么配置的方式如下所示:

 spring:
     freemarker:
            allowRequestOverride: false
            allowSessionOverride: false
            cache: true
            checkTemplateLocation: true
            contentType: text/html
            exposeRequestAttributes: false
            exposeSessionAttributes: false
            exposeSpringMacroHelpers: false
            suffix: .ftl
            templateEncoding: UTF-8
            templateLoaderPath: classpath:/templates/  #表示所有的模板文件都放在该目录下
            spring.freemarker.settings: 
                locale: zh_CN
                date_format: yyyy-MM-dd
                time_format: HH:mm:ss
                datetime_format: yyyy-MM-dd HH:mm:ss

如果你使用的是application.properties,那么配置方式类似的为:

# FREEMARKER (FreeMarkerAutoConfiguration)
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
spring.freemarker.prefix=
spring.freemarker.request-context-attribute=
spring.freemarker.settings.*=
spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/ # comma-separated list
spring.freemarker.view-names= # whitelist of view names that can be resolved

此时我们需要在src/main/resources下建立目录templates,Springboot会自动在加载这个目录下的模板文件。

假设我们的模板文件为index.ftl

<html>
    <body>${key}</body>
</html>

而对应的Controller的写法为

@Controller
public class HomeController{
    @RequestMapping("/")
    public ModelAndView index(){
        ModelAndView mv=new ModelAndView("index");//模板文件的名称,不需要指定后缀
        mv.addObject("key","hello freemaker");
        return mv
    }
}