Spring Boot 初級入門教程(九) —— 新增 JSP 支援
阿新 • • 發佈:2018-12-08
大多數 WEB 開發,都還是用的 JSP 頁面,所以如何讓 SpringBoot 專案支援 JSP,這篇簡單說一下。
一、需要引入依賴的 jar 包。
檢視 pom.xml 檔案中是否引入下面的 jar 包,如果沒有引用,則需要引用才行。
<!-- 該依賴包提供了MVC、AOP等的依賴包 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.0.2.RELEASE</version> </dependency> <!-- 新增JSP頁面支援 --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <version>8.5.31</version> <scope>compile</scope> </dependency>
二、修改配置檔案。
# 配置訪問頁面的字首
spring.mvc.view.prefix=/WEB-INF/pages/
# 配置訪問頁面的字尾
spring.mvc.view.suffix=.jsp
指定 JSP 檔案存放的路徑以及檔案字尾名。
三、新增原始碼目錄。
建立 src/main/webapp 原始碼目錄,其下依次建立 WEB-INF/pages/*.jsp。如圖:
四、編寫 JSP 頁面檔案。
testJspPage.jsp 內容為:
<!DOCTYPE html> <html> <head> <title>TEST JSP PAGE</title> <meta http-equiv="content-type" charset="UTF-8"> <meta name="description" content="JSP測試頁面" /> <style type="text/css"> table { width: 50%; border-collapse: collapse; } table, th, td { border: 1px solid black; } .redfont { color: red; } </style> </head> <body> <table> <tr> <th>DESC</th> <th>VALUE</th> </tr> <tr> <td>String Value From application.properties</td> <td class="redfont">${testSpringCfgStr}</td> </tr> </table> </body> </html>
五、新增測試類。
新建測試類 JspPageController.java,內容如下:
package com.menglanglang.test.springboot.controller; import java.util.Map; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * @desc JSP頁面控制類 * * @author 孟郎郎 * @blog http://blog.csdn.net/tzhuwb * @version 1.0 * @date 2018年7月25日下午5:43:03 */ @Controller @RequestMapping("/jsp") public class JspPageController { @Value("${com.mll.constant.val.str}") public String testSpringCfgStr; /** * 測試Spring配置檔案定義的常量字串 * * @return */ @RequestMapping("/testJspPage") public String testJspPage(Map<String, Object> map) { map.put("testSpringCfgStr", testSpringCfgStr); return "testJspPage"; } }
六、測試
啟動專案,在瀏覽器中訪問 http://localhost:8080/jsp/testJspPage,結果如下:
到此,JSP 支援新增完畢。