1、在pom文件中添加依赖
<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、在application.yml文件中添加配置
spring:
mvc:
view:
prefix: /WEB-INF/view/
suffix: .jsp
3、修改项目文件夹结构如下
新建webapp、WEB-INF、view文件夹
4、在view文件夹下新建 index.jsp文件
jsp内容如下:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<!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>springboot添加jsp支持</title>
</head>
<body>
${username}
<table border="1">
<tr>
<th>序号</th>
<th>用户名</th>
<th>用户ID</th>
<th>账号</th>
</tr>
<c:forEach items="${requestScope.users}" var="user" varStatus="id">
<tr>
<td>${id.index}</td>
<td>${user.userName}</td>
<td>${user.userId}</td>
<td>${user.userCode}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
5、编写实体类
public class User {
private String userId;
private String userName;
private String userCode;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
@Override
public String toString() {
return "User [userId=" + userId + ", userName=" + userName + ", userCode=" + userCode + "]";
}
6、编写controller
@Controller
public class TestController {
@RequestMapping(value = "/test")
public String test(Model model) {
model.addAttribute("username", "明月几时有");
model.addAttribute("users", setList());
return "index";
}
//封装list
public List<User> setList(){
List<User> lists = new ArrayList<User>();
User user1 = new User();
user1.setUserId("1");
user1.setUserCode("001");
user1.setUserName("苏轼");
lists.add(user1);
User user2 = new User();
user2.setUserId("2");
user2.setUserCode("002");
user2.setUserName("李白");
lists.add(user2);
User user3 = new User();
user3.setUserId("3");
user3.setUserCode("003");
user3.setUserName("杜甫");
lists.add(user3);
User user4 = new User();
user4.setUserId("4");
user4.setUserCode("004");
user4.setUserName("白居易");
lists.add(user4);
return lists;
}
}
7、测试代码
浏览器访问 http://localhost:8080/test