SpringBoot添加freemarker模板引擎

1、pom.xml添加依赖:


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

2、配置freemarker的javaConfig

package com.im.adplayer.config;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import freemarker.template.TemplateException;

@Configuration
public class FreemarkerConfig {
	
    @Autowired  
    protected freemarker.template.Configuration configuration;  
    @Autowired  
    protected org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver resolver;  
    @Autowired  
    protected org.springframework.web.servlet.view.InternalResourceViewResolver springResolver;  
    
    @PostConstruct  
    public void  setSharedVariable(){  
        resolver.setSuffix(".ftl");   
        resolver.setCache(false); 
        resolver.setRequestContextAttribute("request"); //为模板调用时,调用request对象的变量名  
        resolver.setOrder(0);  
        resolver.setExposeRequestAttributes(true);
        resolver.setExposeSessionAttributes(true);
    }  
}
3、在src/main/resources下添加一个文件夹templates,添加后缀为.ftl的模板文件,例如:

<#assign base=request.contextPath /> ///这里的request.contextPath ,request这个变量名必须与javaconfig中的setRequestContextAttribute设置的一样,才能取值;



aaaaa

查看卡卷使用记录 <#list card as item>
id open_id nickname groupid gameid cardid code updatetime
${item.id} ${item.open_id} ${item.nickname} ${item.group_id?c} ${item.game_id?c} ${item.card_id} ${item.code} ${item.update_time}
4、如果有一些静态资源需要调用,可以再src/main/resources文件夹下创建static目录,在这个目录下分类创建各种子目录,在模板文件中就可以引用了;

5、Controller

@Controller
public class ModelController {

	@Autowired
	private ConsumeCardMapper consumeCardMapper
	//map(String,Object),前面一个String是在模板中调用时的参数名,后面是实际的参数;
	@RequestMapping("/getconsumeinfo")
	public String getConsumeInfo(Map map) {
		List card = consumeCardMapper.getConsumeCardInfo();
		map.put("card", card);
		return "record";
	}
	
	
	@RequestMapping(value="/index",method=RequestMethod.GET)
	public String index(Map map){
		
		return "index";
	}
}





你可能感兴趣的:(java,Springboot)