1.修改pom.xml文件
<?xml version="1.0" encoding="UTF-8"?> <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> <groupId>cn.ws-h</groupId> <artifactId>08-spring-boot-jsp</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.4.RELEASE</version> </parent> <dependencies> <!--web 启动器--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--tomcat对jsp处理的引擎 springboot默认不推荐用jsp--> <!--jstl--> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <!--jasper--> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok 自动生成-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
</dependencies> </project>
2.创建springboot的全局配置文件 application.properties
#对jsp文件访问的前缀 spring.mvc.view.prefix=/WEB-INF/jsp #对jsp文件访问的后缀 spring.mvc.view.suffix=.jsp
3.创建实体
@Data public class Users { private Integer userid; private String username; private Integer userage; public Users(Integer userid, String username, Integer userage) { this.userid = userid; this.username = username; this.userage = userage; } public Users(int i, String 张三) { super(); } }
4.创建controller
/** * springboot整合jsp */ @Controller public class UserController { /** * 处理请求,产生数据 */ @RequestMapping("/showUser") public String showUser(Model model){ List<Users> list=new ArrayList<>(); list.add(new Users(1,"张三")); list.add(new Users(2,"李四")); list.add(new Users(3,"王五")); //将list传到jsp中,需要一个Model的对象 model.addAttribute("list",list); //视图的跳转 return "userList"; } }
5.创建jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%--导入标签库--%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head> <title>Title</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>
6.创建启动类
/** * SpringBoot的启动类 */ @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class,args); } }