springboot集成freemarker模板引擎

添加依赖


   org.springframework.boot
   spring-boot-starter-web


   org.springframework.boot
   spring-boot-starter-freemarker

配置application.yml

spring:
  freemarker:
    # 设定模板的加载路径,多个以逗号分隔,默认:
    tempalte-loader-path:
      classpath: /templates
    # 是否启用模板缓存
    cache: false
    charset: utf-8
    # 设定模板的后缀
    suffix: .ftl

创建类(可以在普通类中获取到springbean)

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringContextHolder implements ApplicationContextAware {

    private static ApplicationContext applicationContext;
    private static final Logger logger = LoggerFactory.getLogger(IndexController.class.getName());

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext = applicationContext;
    }

    public static void setApplicationContext2(ApplicationContext applicationContext){
        applicationContext = applicationContext;
    }

    public static Object getBean(Class classname){
        try{
            return applicationContext.getBean(classname);
        } catch (Exception e){
            logger.error("###SpringContextHolder.class getBean() ERROR:", e);
        }
        return null;
    }
}

修改启动类

import com.kostal.fota.common.SpringContextHolder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
//@EnableJpaAuditing
@EnableScheduling
@EnableCaching
public class FotaApplication {

	public static void main(String[] args) {
        //SpringApplication.run(FotaApplication.class, args); 修改如下
		ApplicationContext applicationContext = SpringApplication.run(FotaApplication.class, args);
		SpringContextHolder.setApplicationContext2(applicationContext);
	}
}

前端数据交互如下

@RequestMapping("/list")
    public String userlist(Model model){
        model.addAttribute("aaa","bbbbbbbbb");
        return "/user/list";
    }

.ftl页面接收数据如下 

--------------------------------------------分割线-------------------------------------------------------

前端采用的bootstrap框架,引入freemarker模板导致图标显示不出来,报错Failed to decode downloaded font

原因:因为maven的filter解析font文件时,破坏了font文件的二进制格式,导致浏览器解析出错

解决过程:在网上找了些解决办法,和下面的方法一样,刚开始没有生效的原因是因为路径不对,所以我干脆就static目录下都加了进来

解决方法:


    
	    
		    src/main/resources
		    true
		    
		    	static/**
		    
	    
	    
		    src/main/resources
		    false
		    
			    static/**
		    
	    
    

 

你可能感兴趣的:(freemarker)