springboot整合jsp


前言

本篇文章主要介紹的是springboot整合jsp。

Jsp簡介

JSP全稱Java Server Pages,是一種動態網頁開發技術。它使用JSP標簽在HTML網頁中插入Java代碼。標簽通常以<%開頭以%>結束。

JSP是一種Java servlet,主要用於實現Java web應用程序的用戶界面部分。網頁開發者們通過結合HTML代碼、XHTML代碼、XML元素以及嵌入JSP操作和命令來編寫JSP。

GitHub源碼鏈接位於文章底部。

項目結構


如果沒有webapp目錄,則需要在Java與resources的同級目錄下創建。並將其設置為web資源的文件夾。菜單欄中File-Project Structure

pom文件中添加依賴:
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </dependency>
        <!-- SpringBoot 外部tomcat支持 -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
    </dependencies>
application.yml文件中配置:
server:
  port: 8080

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

根據這里的配置,我們需要在webapp目錄下創建WEB-INF文件夾,在WEB-INF文件夾下創建jsp文件夾存放jsp頁面。

在剛剛創建的目錄中新建一個index.jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
Jsp測試頁面
</body>
</html>

JspController中添加接口:

@Controller
public class JspController {
    @RequestMapping("/index")
    public String index() {
        return "index";
    }
}

通過啟動類啟動程序后,訪問localhost:8080/index 接口,返回index.jsp視圖。

啟動后訪問jsp報404的原因:

1.yml文件中配置的jsp路徑與jsp頁面在項目中的路徑不一致

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

要將webapp目錄設置為web資源文件夾,設置方法文章上面有提過;在webapp文件夾下創建WEB-INF文件夾,在WEB-INF文件夾下創建jsp文件夾,在jsp文件夾下存放jsp文件。

2.在多模塊的情況下,需要手動設置工程的Working directory

3.springboot打包方式為jar也會報404,改為war即可。

本文GitHub源碼:https://github.com/lixianguo5097/springboot/tree/master/springboot-jsp

CSDN:https://blog.csdn.net/qq_27682773
簡書:https://www.jianshu.com/u/e99381e6886e
博客園:https://www.cnblogs.com/lixianguo
個人博客:https://www.lxgblog.com


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM