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); }
访问接口方法映射路径
Copyright © 2023 leiyu.cn. All Rights Reserved. 磊宇云计算 版权所有 许可证编号:B1-20233142/B2-20230630 山东磊宇云计算有限公司 鲁ICP备2020045424号
磊宇云计算致力于以最 “绿色节能” 的方式,让每一位上云的客户成为全球绿色节能和降低碳排放的贡献者