SpringBoot整合Freemarker
由于JSP已经被淘汰,现在基本不会去使用JSP,一般springboot会使用的页面有freemarker模板和thymeleaf模板。
可以了解一下整合freemarker模板,下一篇再说thymeleaf模板,我一般使用的是thymeleaf模板,后缀名是html看着就舒服,而且官方也是推荐使用thymeleaf模板。
好了,不说那么多了,开始整合freemarker模板吧
首先需要在pom文件中添加freemarker依赖项,但是也要web启动器,不然,你会发现你用@Controller注解都用不了
pom.xml
<!-- web启动器-->
<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>
创建一个ftl文件,作为页面,当然是放在resources下的templates下,因为springboot默认访问页面的地址就在这里。
userList.ftl
<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.userid}</td>
<td>${user.username}</td>
<td>${user.userage}</td>
</tr>
</#list>
</table>
</body>
</html>
controller控制的设置访问页面
UserController
package com.kevin.controller;
import java.util.ArrayList;
import java.util.List;
import com.kevin.entity.Users;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author kevin
* @version 1.0
* @description springboot整合freemarker
* @createDate 2019/3/13
*/
@Controller
public class UserController {
// 访问地址: localhost:8080/showUser
/*
* 处理请求,产生数据
*/
@RequestMapping("/showUser")
public String showUser(Model model){
List<Users> list = new ArrayList<>();
list.add(new Users(1,"张三",20));
list.add(new Users(2,"李四",22));
list.add(new Users(3,"王五",24));
//需要一个Model对象
model.addAttribute("list", list);
//跳转视图
return "userList";
}
}
实体类
package com.kevin.entity;
/**
* @author kevin
* @version 1.0
* @description
* @createDate 2019/3/13
*/
public class Users {
private Integer userid;
private String username;
private Integer userage;
public Users() {
}
public Users(Integer userid, String username, Integer userage) {
super();
this.userid = userid;
this.username = username;
this.userage = userage;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getUserage() {
return userage;
}
public void setUserage(Integer userage) {
this.userage = userage;
}
}
启动类
package com.kevin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author kevin
* @version 1.0
* @description springboot整合freemarker
* @createDate 2019/3/13
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
整体的目录
访问页面看看:localhost:8080/showUser
可以访问,证明整合成功。