虽然说作为视图技术,JSP不是SpringBoot中提倡的,但是在实际开发中很多人还是离不开JSP技术的,因此在这里我们简单的整合使用一下。
1.创建项目
2.修改pom文件,添加坐标
<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.3.RELEASE</version> </parent> <groupId>com.neuedu</groupId> <artifactId>08-spring-boot-view-jsp</artifactId> <version>0.0.1-SNAPSHOT</version> <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坐标:支持JSP --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <!-- 打包的时候,不用把该jar包打包进去 --> <scope>provided</scope> </dependency> </dependencies> </project>
3.创建SpringBoot的全局配置文件,application.properties
配置视图解析器,修改application.properties如下:
spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp
4.创建Controller
package com.neuedu.controller; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.neuedu.po.User; /** * SpringBoot 整合 jsp * @author 清水三千尺 * */ @Controller public class UserController { /* * 处理请求,产生数据(模拟数据) */ @RequestMapping("/showUser") public String showUser(Model model) { //准备模拟数据 List<User> list = new ArrayList<User>(); list.add(new User(1, "赵四", 45)); list.add(new User(2, "刘能", 39)); list.add(new User(3, "广坤", 43)); //需要一个Model对象 model.addAttribute("list",list); //跳转视图 return "userList"; } }
5.创建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>
6.创建启动类
package com.neuedu; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * SpringBoot 启动类 * @author 清水三千尺 * */ @SpringBootApplication public class App { public static void main(String[] args) throws Exception { SpringApplication.run(App.class, args); } }
7.测试
访问路径:http://localhost:8080/showUser