首先先下载依赖:
<!--freeMarker模板--> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-freemarker --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> <version>2.1.3.RELEASE</version> </dependency>
然后配置freemarker的配置信息:
#freeMarker配置 #request属性是否可以覆盖controller中model的同名项 spring.freemarker.allow-request-override=false #httpsession的属性是否可以覆盖controller中的model的同名项 spring.freemarker.allow-session-override=false #是否开启缓存 spring.freemarker.cache=false #模板文件编码 spring.freemarker.charset=UTF-8 #检查模板文件位置 spring.freemarker.check-template-location=true #content-type的值 spring.freemarker.content-type=text/html #是否将HHttpServletRequest中的属性添加到model中 spring.freemarker.expose-request-attributes=false #是否将HHttpSession中的属性添加到model中 spring.freemarker.expose-session-attributes=false #模板文件后缀 spring.freemarker.suffix=.ftl #模板文件位置 spring.freemarker.template-loader-path=classpath:/templates/
然后在resources下新建一个templates目录,默认路径
下面通过一个简单的例子来看一下:
@Controller public class BookController { // @Autowired // Book book; @GetMapping("/seeBook") public ModelAndView seeBook() { System.out.println("调用seeBook方法"); Book b1 = new Book(); b1.setName("三国演义"); b1.setAuthor("罗贯中"); b1.setPrice(25f); b1.setTimes("2019-8-9"); Book b2 = new Book(); b2.setName("红楼梦"); b2.setAuthor("曹雪芹"); b2.setPrice(27f); b2.setTimes("2019-9-9"); List<Book> books = new ArrayList<>(); books.add(b1); books.add(b2); // 返回视图 ModelAndView mv = new ModelAndView(); // mv.addObject("books",books); // mv.setViewName("books"); mv.addObject("booksfree",books); mv.setViewName("booksfree"); return mv; } }
新建模板文件:freebooks.ftl
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>图书列表</title> </head> <body> <table border="1"> <tr> <td>图书名称</td> <td>图书作者</td> <td>图书价格</td> <td>出版时间</td> </tr> <#if booksfree ??&&(booksfree?size>0)> <#list booksfree as book> <tr> <td>${book.name}</td> <td>${book.author}</td> <td>${book.price}</td> <td>${book.times}</td> </tr> </#list> </#if> </table> </body> </html>
那么我们看一下结果: