关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

springboot使用freemarker的入门Demo

发布时间:2023-06-30 23:28:40

1.创建一个maven web项目

2.添加所需要的依赖

 org.springframework.boot spring-boot-starter-parent 2.0.3.RELEASE   org.springframework.boot spring-boot-starter-web   org.springframework.boot spring-boot-starter-freemarker

   

3.写一个接口,返回到src/main/resources/templates/test.ftl页面(freemarker默认模板后缀为ftl,默认路径是src/main/resources/templates,可以在application.properties中更改配置)

@RestController @RequestMapping("/test") public class Test {   @SuppressWarnings("all")  @RequestMapping("/fun1")  public ModelAndView fun(HttpServletRequest request) {  ModelAndView mv = new ModelAndView("/test");  mv.addObject("name","vhukze");  mv.addObject("sex",1);  ArrayList list = new ArrayList();  list.add("1");  list.add("2");  list.add("3");  mv.addObject("list", list);  return mv;  } }

   

配置信息

## Freemarker 配置 ##模版存放路径(默认为 classpath:/templates/) spring.freemarker.template-loader-path=classpath:/templates/ ##是否生成缓存,生成环境建议开启(默认为true) spring.freemarker.cache=false ##编码 spring.freemarker.charset=UTF-8 spring.freemarker.check-template-location=true ##content-type类型(默认为test/html) spring.freemarker.content-type=text/html ## 设定所有request的属性在merge到模板的时候,是否要都添加到model中(默认为false) spring.freemarker.expose-request-attributes=false ##设定所有HttpSession的属性在merge到模板的时候,是否要都添加到model中.(默认为false) spring.freemarker.expose-session-attributes=false ##RequestContext属性的名称(默认为-) spring.freemarker.request-context-attribute=request ##模板后缀(默认为.ftl) spring.freemarker.suffix=.html

   

4.书写test.ftl文件

  Hello World! ${name}    女    男      ${num}

   

跟EL表达式一样的取值 ${}

判断语句 <#if>  <#elseif> <#else> 

遍历集合 <#list as=""> 

这个就相当于java中的forEach语句

for (String num : list) {  System.out.println(num); }

   

访问接口方法映射路径


/template/Home/leiyu/PC/Static