SpringBoot整合视图层:整合JSP
SpringBoot学习目录
创建项目
修改pom.xml文件
添加对JSP支持的依赖
<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.1.RELEASE</version>
</parent>
<groupId>com.znk</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- jdk1.7 -->
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- springBoot 的启动器 -->
<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>
创建全局配置文件
application.properties:
添加前后缀,Controller层可通过(return 视图名)跳转相应JSP
#添加访问前缀
spring.mvc.view.prefix=/WEB-INF/jsp/
#添加访问后缀
spring.mvc.view.suffix=.jsp
创建Controller
实体类Users略
/**
* SpringBoot 整合 jsp
*
*/
@Controller
public class UserController {
/*
* 处理请求,产生数据
*/
@RequestMapping("/showUser")
public String showUser(Model model){
List<Users> list = new ArrayList<>();
list.add(new Users(1,"小王",18));
list.add(new Users(2,"小明",19));
list.add(new Users(3,"小红",17));
//需要一个 Model 对象
model.addAttribute("list", list);
//跳转视图
return "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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; 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>
创建启动类
Application.java:
/**
* SpringBoot 启动类
*
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
启动项目,访问localhost:8080/showUser