玩轉 SpringBoot 2 快速整合 | JSP 篇

前言

JavaServer Pages(JSP)技術使Web開發人員和設計人員能夠快速開發和輕鬆維護利用現有業務系統的信息豐富的動態Web頁面。

作爲Java技術系列的一部分,JSP技術可以快速開發獨立於平臺的基於Web的應用程序。JSP技術將用戶界面與內容生成分開,使設計人員能夠在不改變底層動態內容的情況下更改整體頁面佈局。

對開發人員的好處
如果您是熟悉HTML的網頁開發人員或設計人員,則可以:

  • 使用JSP技術而不必學習Java語言:您可以使用JSP技術而無需學習如何編寫Java scriplet。儘管不再需要scriptlet來生成動態內容,但仍然支持它們以提供向後兼容性。
  • 擴展JSP語言:Java標記庫開發人員和設計人員可以使用“簡單標記處理程序”擴展JSP語言,該標記處理程序使用新的,更簡單,更清晰的標記擴展API。這刺激了可用的可插拔,可重用標記庫的數量不斷增加,從而減少了編寫功能強大的Web應用程序所需的代碼量。
  • 輕鬆編寫和維護頁面: JavaServer Pages標準標記庫(JSTL)表達式語言現已集成到JSP技術中,並已升級爲支持功能。現在可以使用表達式語言而不是scriptlet表達式。

——以上內容摘自自 Oracle 關於JSP的介紹 鏈接地址:https://www.oracle.com/technetwork/java/overview-138580.html

雖然現在 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 步驟如下:

  1. 引入 spring-boot-starter-tomcat 依賴 並且 scopeprovided
  2. 在 application.properties 配置文件中將視圖設置成jsp
  3. 創建src/main/webapp 目錄下創建 WEB-INF 目錄並在該目錄下創建 JSP 文件
  4. 創建訪問 JSP 的 Controller

代碼示例

具體代碼示例請查看我的 GitHub 倉庫 springbootexamples 中模塊工程名: spring-boot-2.x-jsp 進行查看

Github:https://github.com/zhuoqianmingyue/springbootexamples
如果您對這些感興趣,歡迎 star、或點贊給予支持!轉發請標明出處!

參考文獻

https://github.com/spring-projects/spring-boot/tree/v2.0.6.RELEASE/spring-boot-samples/spring-boot-sample-web-jsp 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章