整合freemarker要求必须将视图文件放在 src/main/resources下的templates文件夹下,该文件夹是安全的不可直接访问的,必须由controller之类的接受请求类去跳转,因为如果直接访问就意味着需要及时响应,而springboot需要给展示文件去渲染,这需要时间,所以他是不允许被直接访问的。
1.pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.10.RELEASE</version> </parent> <groupId>com.mr.li</groupId> <artifactId>springboot_004</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <java.version>1.7</java.version> </properties> <dependencies> <!-- 添加启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- freemarker启动器:使用模板开发--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> </dependencies> </project>
2.实体类
package com.mr.li.pojo; public class User { private int id; private String name; private int age; public User(int id, String name, int age) { super(); this.id = id; this.name = name; this.age = age; } public User() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
3.controller
package com.mr.li.controller; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.mr.li.pojo.User; @Controller public class MyController { @RequestMapping("/show") public String show(Model model) { //生成jsp页面需要展示的数据源 List<User> list = new ArrayList<User>(); list.add(new User(1, "小明", 15)); list.add(new User(2, "小红", 16)); list.add(new User(3, "小丽", 17)); //这里前面的list是在jsp中使用EL表达式所使用的名称 model.addAttribute("list", list); //这里返回的是jsp页面名称,前后缀在配置文件中 return "users"; } }
5.users.ftl 此文件名字叫users因为controller中show方法返回的名字叫users,里面的EL表达式中的list是controller类中的model对象的addAttribute方法的key,参数名为list.
<html> <head> <title>展示用户数据</title> <meta charset="utf-9"></meta> </head> <body> <table border="1" align="center" width="50%"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> </tr> <#list list as user > <tr> <td>${user.id}</td> <td>${user.name}</td> <td>${user.age}</td> </tr> </#list> </table> </body> </html>
访问的url: http://localhost:8080/show
项目结构:
原文地址:https://www.cnblogs.com/li-yan-long/p/10777212.html
时间: 2024-10-06 17:26:11