1. pom.xml中添加jstl和jasper
springboot不推荐使用jsp,所以在spring-boot-starter-web启动器中并没有包括这两个,所以我们需要单独引入:
<!-- jstl --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <!-- jasper:jsp引擎 --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency>
2. 在src/main/resources目录下创建application.properties,添加jsp的视图映射
#jsp映射配置 spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp
3. 编写controller
public class User { private Integer userId; private String userName; private Integer age; public User() { } public User(Integer userId, String userName, Integer age) { this.userId = userId; this.userName = userName; this.age = age; } 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 getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
@RestController public class UserController { @RequestMapping("/findUserList") public Object findUserList(Model model){ List<User> list = new ArrayList<User>(); list.add(new User(1, "张三", 20)); list.add(new User(2, "李四", 27)); list.add(new User(3, "王五", 30)); model.addAttribute("list",list); //因为使用@RestController注解,所以要返回视图,必须使用ModelAndView ModelAndView view = new ModelAndView(); view.addObject(model); view.setViewName("userList");//视图名称 return view; } }
4. 在src/main下创建webapp
前面在application.properties中,已添加了jsp的视图映射,所以在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 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>用户列表</title> </head> <body> <table> <thead> <tr> <th>Id</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <c:forEach items="${list}" var="user"> <tr> <td>${user.userId }</td> <td>${user.userName }</td> <td>${user.age }</td> </tr> </c:forEach> </tbody> </table> </body> </html>
5. 编写启动类,执行main方法,访问浏览器:http://localhost:8080/findUserList