Spring Boot 整合jsp Spring Boot 整合Freemarker Spring Boot 整合 Thymeleaf (重點講解,官方推薦)
步驟:html
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.4.RELEASE</version> </parent> <dependencies> <!-- spring boot web啓動器 --> <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> </dependency> </dependencies>
@Controller public class UserController { /** * 獲取用戶信息,到jsp頁面進行展現 */ @RequestMapping("/userList") public String getUsersAll(Model model) { //訪問業務層-->數據訪問層mapper-->mybatis數據庫獲取全部用戶信息 //模擬,定義固定的用戶信息 List<User> list=new ArrayList<User>(); list.add(new User("007", "小張", 22)); list.add(new User("009","小康",32)); list.add(new User("012","小健",18)); model.addAttribute("list", list); //配置springmvc的視圖解析器,前綴:/WEB-INF/ 後綴: .jsp return "index"; } }
#配置jsp的訪問的前綴和後綴 (視圖解析器) spring.mvc.view.prefix=/WEB-INF/ spring.mvc.view.suffix=.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> <html> <head> <meta charset="UTF-8"> <title>用戶顯示頁面</title> </head> <body> <table border="1" width="60%" align="center"> <tr> <td>用戶編號</td> <td>用戶名稱</td> <td>年齡</td> </tr> <c:forEach items="${list}" var="user"> <tr> <td>${user.id}</td> <td>${user.username}</td> <td>${user.age}</td> </tr> </c:forEach> </table> </body> </html>
@SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
<dependencies> <!--spring boot web 啓動器座標 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- freemarker 啓動器座標 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> </dependencies>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>用戶顯示頁面</title> </head> <body> <table border="1" width="60%" align="center"> <tr> <td>用戶編號</td> <td>用戶名稱</td> <td>年齡</td> </tr> <!--freemarker獲取request傳過來的數據 <#數據類型 key類型 as 遍歷元素名稱>--> <#list list as user> <tr> <td>${user.id}</td> <td>${user.username}</td> <td>${user.age}</td> </tr> </#list> </table> </body> <html>
# 模板編碼。 spring.freemarker.charset= UTF-8 # 後綴,在構建URL時附加到查看名稱。 spring.freemarker.suffix=.ftl # 逗號分隔的模板路徑列表。src/main/resources==classpath spring.freemarker.template-loader-path=classpath:/templates/ server.port=8081
@SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
運行
java