SpringBoot整合jsp
1.修改pom文件加入两个坐标jstl标签库和jasper
<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>2.1.2.RELEASE</version>
</parent>
<groupId>com.dxh</groupId>
<artifactId>08-spring-boot-view-jsp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- 修改JDK版本 -->
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- Spring Boot 的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- jstl标签库-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- jasper -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
2.创建springboot的全局配置文件(位于classpath根目录),application.properties
#前缀
spring.mvc.view.prefix=/WEB-INF/jsp/
#后缀
spring.mvc.view.suffix=.jsp
3.创建controller和pojo
@Controller
public class UserController {
/**
* 处理请求,产生数据
*/
@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,"赵武",25));
//需要一个Model对象
model.addAttribute("list",list);
//跳转视图
return "userList";
}
}
public class Users {
private Integer userId;
private String userName;
private Integer userAge;
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;
}
}
4.创建jsp页面
- 注意页面位置(application.properties中定义的) src/main/webapp/WEB-INF/jsp/userList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table border="1" align="center" width="50%">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
<c:forEach items="${list}" var = "user">
<tr>
<td>${user.userId}</td>
<td>${user.userName}</td>
<td>${user.userAge}</td>
</tr>
</c:forEach>
</table>
</body>
</html>