1. pom.xml to add jstl and jasper
springboot not recommended jsp, it did not include the two in springboot-starter-web launcher, so we need to introduce separately:
<!-- 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. Create application.properties in src / main / resources directory, add jsp view map
#jsp mapping configuration spring.mvc.view.prefix = / the WEB-INF / JSP / spring.mvc.view.suffix = .jsp
3. Write 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); new new ModelAndView View =because the use of @RestController notes, so to return to the view, you must use ModelAndView// ModelAndView(); view.addObject(model); view.setViewName("userList");//视图名称 return view; } }
4. Create webapp in src / main
In front application.properties, the map view has been added jsp, so to create a WEB-INF / jsp in the webapp directory, and create 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. Start writing class, execute the main method to access the browser: HTTP: // localhost: 8080 / findUserList