玩轉 SpringBoot 2 快速整合 | JSP 篇

前言

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

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

對開發人員的好處
若是您是熟悉HTML的網頁開發人員或設計人員,則能夠:git

  • 使用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.htmlgithub

雖然如今 JSP基本已經淘汰,可是不少公司的老的項目仍是在用 JSP 做爲頁面,經過閱讀該篇博客,你將瞭解到如何在SpringBoot 中快速使用 JSP 簡單操做。web

SpringBoot 使用 JSP 操做步驟

第一步在 pom.xml 添加支持 JSP 視圖的依賴,具體代碼以下:spring

<!-- 非必選 -->        
<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 相關配置信息,具體配置信息以下:apache

server.port=8080
server.servlet.context-path=/sbe

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

第三步建立 src/main/webapp 目錄並在該目錄建立 JSP。segmentfault

添加JSP文件的路徑位置以下圖所示:tomcat

圖片圖片

JSP 文件內容以下:springboot

<%@ 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 

相關文章
相關標籤/搜索