玩轉 SpringBoot 2 快速整合 | JSP 篇
前言
JavaServer Pages(JSP)技術使Web開發人員和設計人員能夠快速開發和輕鬆維護利用現有業務系統的資訊豐富的動態Web頁面。
作為Java技術系列的一部分,JSP技術可以快速開發獨立於平臺的基於Web的應用程式。JSP技術將使用者介面與內容生成分開,使設計人員能夠在不改變底層動態內容的情況下更改整體頁面佈局。
對開發人員的好處如果您是熟悉HTML的網頁開發人員或設計人員,則可以:
- 使用JSP技術而不必學習Java語言:您可以使用JSP技術而無需學習如何編寫Java scriplet。儘管不再需要scriptlet來生成動態內容,但仍然支援它們以提供向後相容性。
-
擴充套件JSP語言
- 輕鬆編寫和維護頁面: JavaServer Pages標準標記庫(JSTL)表示式語言現已整合到JSP技術中,並已升級為支援功能。現在可以使用表示式語言而不是scriptlet表示式。
——以上內容摘自自 Oracle 關於JSP的介紹 連結地址:www.oracle.com/technetwork…
雖然現在 JSP基本已經淘汰,但是很多公司的老的專案還是在用 JSP 作為頁面,通過閱讀該篇部落格,你將瞭解到如何在SpringBoot 中快速使用 JSP 簡單操作。
SpringBoot 使用 JSP 操作步驟
第一步在 pom.xml 新增支援 JSP 檢視的依賴,具體程式碼如下:
<!-- 非必選 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- Provided 編譯和測試的時候使用-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- 對jsp的支援的依賴 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency> 複製程式碼
第二步在 application.properties 配置檔案中新增 JSP 相關配置資訊,具體配置資訊如下:
server.port=8080
server.servlet.context-path=/sbe
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp複製程式碼
第三步建立 src/main/webapp 目錄並在該目錄建立 JSP。
新增JSP檔案的路徑位置如下圖所示:
JSP 檔案內容如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
${welcome}
</body>
</html>複製程式碼
第四步建立訪問 JSP 頁面的 Controller。
package cn.lijunkui.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping()
public class JspController {
@RequestMapping("/helloworld")
public String toJps(Model model) {
model.addAttribute("welcome","不建議使用jsp");
return "welcome";
}
}複製程式碼
測試
在遊覽器輸入訪問 JSP 頁面的 Controller 的 URL:http://localhost:8080/sbe/helloworld 進行測試,測試結果如下:
小結
SpringBoot 使用 JSP 步驟如下:
- 引入 spring-boot-starter-tomcat 依賴 並且 scope為 provided
- 在 application.properties 配置檔案中將檢視設定成jsp
- 建立src/main/webapp 目錄下建立 WEB-INF 目錄並在該目錄下建立 JSP 檔案
- 建立訪問 JSP 的 Controller
程式碼示例
具體程式碼示例請檢視我的 GitHub 倉庫 springbootexamples 中模組工程名: spring-boot-2.x-jsp 進行檢視
Github:github.com/zhuoqianmin…如果您對這些感興趣,歡迎 star、或點贊給予支援!轉發請標明出處!