Java -- springboot 配置 freemarker

1、添加依赖

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

2、配置application.properties

spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.charset=utf-8
spring.freemarker.cache=false
spring.freemarker.suffix=.ftl

spring.freemarker.request-context-attribute=request

3、创建资源目录

resources 下创建 templates 目录,新增 index.ftl 文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    ${name}
</body>
</html>

4、编写控制器

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class TestController {

    @RequestMapping(value = "/test")
    public String test(Model model){
        model.addAttribute("name", "admin");
        return "index";
    }
}

5、注意事项

freemarker 文件中的 js 引用一定要加闭合标签,且不能使用/>

6、模板方法

  • template类
package com.vim.common.freemarker;

import com.vim.common.constants.Global;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModelException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DictListTemplate implements TemplateMethodModelEx {

    @Override
    public Object exec(List arguments) throws TemplateModelException {
        return Global.getDictList(arguments.get(0).toString());
    }

}
  • 注册模板类
package com.vim.common.config;

import com.vim.common.freemarker.DictListTemplate;
import freemarker.template.TemplateModelException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;

@Configuration
public class FreemarkerConfig {

    @Autowired
    private ServletContext servletContext;
    @Autowired
    private freemarker.template.Configuration configuration;

    @PostConstruct
    public void setVariableConfiguration() throws TemplateModelException {
        //路径变量
        configuration.setSharedVariable("ctx", servletContext.getContextPath());
        configuration.setSharedVariable("ctxStatic", servletContext.getContextPath() + "/statics");
        //字典数据
        configuration.setSharedVariable("dictList", new DictListTemplate());
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值