1. 程式人生 > 程式設計 >Springboot整合jsp及部署伺服器實現原理

Springboot整合jsp及部署伺服器實現原理

1.在application配置檔案裡面加入配置:

spring:
 mvc:
  view:
   prefix: /jsp/
   suffix: .jsp

2.手動在src->main->下面建立webapp資料夾

3.在Springboot 啟動類加入如下程式碼:

@Bean
  public InternalResourceViewResolver setupViewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/jsp/");
    resolver.setSuffix(".jsp");
    return resolver;
  }

4.在webapp->下面建立jsp資料夾放入你的jsp檔案

這個時候目錄層級大概應該是這樣的

Springboot整合jsp及部署伺服器實現原理

5.在pom檔案裡面加入jsp依賴

<!--      jsp -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
    </dependency>
    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>
    <!--    jsp-->

這個時候jsp是可以正常訪問的。

但是部署到伺服器之後就會出現404錯誤(我出現了這個錯誤。)

解決辦法:

在pom檔案中加入程式碼:

<plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
                <!-- 這一部分是加入的內容 <version>1.4.2.RELEASE</version> -->
        <!-- 解決部署之後jsp訪問404 問題 只能springboot 啟動類main其他main都要註釋或者刪除 -->
        <version>1.4.2.RELEASE</version>
        <configuration>
          <fork>true</fork>
          <includeSystemScope>true</includeSystemScope>
        </configuration>
      </plugin>

             <!--  解決訪問打包時忽略webapp問題 使用命令 打包 mvn clean install -Dmaven.test.skip=true -->
    <!-- resources外掛,在打jar包時可以將webapp目錄下的檔案進行打包 -->
    <resources>
      <resource>
        <!-- 指定resources外掛處理哪個目錄下的資原始檔 -->
        <directory>src/main/webapp</directory>
        <!--注意此次必須要放在此目錄下才能被訪問到 -->
        <targetPath>META-INF/resources</targetPath>
        <includes>
          <include>**/**</include>
        </includes>
      </resource>
      <!-- 將專案中的配置檔案,打包至classes下面 -->
      <resource>
        <directory>src/main/resources</directory>
      </resource>
    </resources>

因為據網上的資料說超過這個版本之後就不行了,具體原因未深究。

至此從新打包部署之後jsp應該就可以正常訪問了

然後我這邊做法是把資原始檔都放到伺服器了 js css img等等這些資源

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。