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 [email protected]
*/
@Configuration
public 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 的别名
本人已经在开源框架lenos中实现,如果你感兴趣,或者需要帮助,可以下载学习:
地址:https://gitee.com/bweird/lenosp
lenos是一款快速开发脚手架,不仅有定时任务,还有权限管理,日志监控等其他技术,如果你喜欢 别忘记点个star,谢谢。如果有疑问,可以在lenos:137738503下加群询问。