做人第一 学习第二

spring boot整合 freemarker 详细教程

spring boot 我们都知道是一个简化配置的服务,省去繁琐的xml配置,以properties和yml还有 注解形式来替代之前的xml配置。

我们首先实现spring boot 对freemarker的支持,引入pom

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

 

在yml中添加配置项:

spring:    
        freemarker:
                template-loader-path: classpath:/ftl/

classpath后面为前缀。也可以在注解配置类中实现

新建配置类:FreeMarkerConfig.java

import com.jagregory.shiro.freemarker.ShiroTags;import freemarker.template.TemplateException;import freemarker.template.TemplateModelException;import java.io.IOException;import java.util.Properties;import javax.annotation.PostConstruct;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.ui.freemarker.FreeMarkerConfigurationFactory;import org.springframework.web.servlet.ViewResolver;import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;/**
 * @author zhuxiaomeng
 * @date 2018/1/2.
 * @email 154040976@qq.com
 */@Configurationpublic class FreeMarkerConfig {  @Bean
  public ViewResolver viewResolver() {
    FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
    resolver.setCache(false);
    resolver.setViewClass(org.springframework.web.servlet.view.freemarker.FreeMarkerView.class);
    resolver.setRequestContextAttribute("re");
    resolver.setExposeSpringMacroHelpers(true);
    resolver.setExposeRequestAttributes(true);
    resolver.setExposeSessionAttributes(true);
    resolver.setSuffix(".ftl");
    resolver.setContentType("text/html; charset=UTF-8");    return resolver;
  }  @Bean
  public FreeMarkerConfigurer freemarkerConfig() throws IOException, TemplateException {
    FreeMarkerConfigurationFactory factory = new FreeMarkerConfigurationFactory();
    factory.setTemplateLoaderPaths("classpath:/ftl/", "src/main/resources/ftl");
    factory.setDefaultEncoding("UTF-8");
    FreeMarkerConfigurer result = new FreeMarkerConfigurer();
    freemarker.template.Configuration configuration = factory.createConfiguration();
    configuration.setClassicCompatible(true);
    result.setConfiguration(configuration);
    Properties settings = new Properties();
    settings.put("template_update_delay", "0");
    settings.put("default_encoding", "UTF-8");
    settings.put("number_format", "0.##########");
    settings.put("datetime_format", "yyyy-MM-dd HH:mm:ss");
    settings.put("classic_compatible", true);
    settings.put("template_exception_handler", "ignore");
    result.setFreemarkerSettings(settings);    return result;
  }
}

setRequestContextAttribute:设置属性名称,为freemarker前端 RequestContext 的别名

 


此文如未标注转载均为本站原创,自由转载请表明出处 宋子宪博客 » spring boot整合 freemarker 详细教程

发表评论

游客 表情
送你一朵小花花~

帅人已评:(0)