前言
本章学习SpringBoot对视图层技术的支持
方法
1.概念
本章讲解SpringBoot整合JSP和FreeMarker的相关知识,整合Thymeleaf将在后续中的概念讲解!
2.整合JSP
1)如果依然使用我们之前的JSP视图的话,对于SpringBoot来讲需要额外配置下jar包,因为它并不是建议我们使用JSP
<!-- 整合JSP需要引入的依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
2)创建SpringBoot全局配置文件application.properties
3)编写实体类Users
package cn.edu.ccut.bo;
public class Users {
private Integer id;
private String name;
private Integer age;
public Users(Integer id, String name, Integer age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public Users() {
super();
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
4)编写controller
package cn.edu.ccut.controller;
import java.util.List;
import java.util.ArrayList;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.edu.ccut.bo.Users;
@Controller
public class UserController {
@RequestMapping("/showUser")
public String getUsers(Model model){
List<Users> list = new ArrayList<>();
list.add(new Users(1, "张三", 25));
list.add(new Users(2, "李四", 26));
list.add(new Users(3, "王五", 27));
list.add(new Users(4, "赵六", 28));
model.addAttribute("userList", list);
return "userList";
}
}
5)编写JSP文件
<%@ page language="java" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<title>用户列表</title>
</head>
<body>
<table border="0" >
<tr>
<th>用户id</th>
<th>用户名称</th>
<th>用户年龄</th>
</tr>
<c:forEach items="${userList }" var="user">
<tr>
<td>${user.id }</td>
<td>${user.name }</td>
<td>${user.age }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
6)启动程序,访问http://localhost:8080/showUser
3.整合FreeMarker
1)添加freemarker启动器
<!-- 配置freemarker启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2)创建freemarker模板
注意:模板类文件的存放位置是有讲究的,必须存放在src/main/resources/templates/下
userList.ftl:
<!DOCTYPE html>
<html>
<head>
<title>用户列表</title>
</head>
<body>
<table border="0" >
<tr>
<th>用户id</th>
<th>用户名称</th>
<th>用户年龄</th>
</tr>
<#list userList as user>
<tr>
<td>${user.id }</td>
<td>${user.name }</td>
<td>${user.age }</td>
</tr>
</#list>
</table>
</body>
</html>
3)编写controller
controller的编写内容和上面整合JSP的内容一致。
4)启动程序,访问http://localhost:8080/showUser
可见,springBoot对于freemarker还是没有赶尽杀绝的,JSP的形式不容乐观!!!