SpringBoot專案中的檢視解析器問題(兩種)
前言:SpringBoot官網推薦使用HTML檢視解析器,但是根據個人的具體業務也有可能使用到JSP檢視解析器,所以這裡我給大家簡單介紹一下這兩種檢視解析器的具體使用
一、解析成JSP頁面
1.在pom.xml檔案中新增相關依賴
<dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <!-- tomcat的支援--> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency>
2.在application.properties配置檔案中配置字首與字尾
spring.mvc.view.prefix=/jsp/ spring.mvc.view.suffix=.jsp
注:如果是使用官網的SpringBoot專案,這裡可能出現一個小問題,如果不借助任何模板引擎( thymeleaf )的話,JSP頁面放在resources目錄下(包括預設的幾個子目錄)是訪問不到的!,那麼這時候就得自己配置一個目錄去存放JSP頁面
解決方案:
(1)可以在resources目錄下新建一個 META-INF 目錄,然後在 META-INF 目錄下建立一個resources目錄,然後把需要的jsp頁面放在這個目錄下面,接著在application.properties 配置檔案中配置一下訪問路徑,就可以訪問到jsp檔案了:
(2)在 resources 目錄同級別的目錄下面建立 webapp 目錄,然後把需要的jsp頁面放在webapp目錄下面,也是可以訪問的:
(3)經過測試發現,如果以上兩個目錄都存在,優先訪問的是與resources目錄同級別的webapp目錄下的jsp頁面:
(4)使用模板引擎 thymeleaf 來測試一下直接放在 resources 目錄下的templates 目錄下的jsp頁面:
1)在pom.xml中配置模板引擎thymeleaf 依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2)在 application.properties 檔案中配置 thymeleaf 相關屬性值,最後在 templates 目錄下建立 jsp檔案就可以了:
二、解析成HTML頁面
1.在pom.xml中引入模板引擎 thymeleaf依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2.在 application.properties 檔案中配置 thymeleaf 相關屬性值,最後在 templates 目錄下建立html檔案就可以了:
三、總結
當JSP檢視解析器與模板引擎thymeleaf共存的時候,SpringBoot會預設解析模板引擎thymeleaf的配置。在模板引擎thymeleaf的配置中,如果都不配置的話,會預設解析templates目錄下的HTML檔案,即預設字首為"/templates/",預設字尾為".html",最後強調一點,在SpringBoot中,根據官網推薦,我們最好使用模板引擎和HTML頁面來編寫程式碼!
到此這篇關於SpringBoot專案中的檢視解析器問題(兩種)的文章就介紹到這了,更多相關SpringBoot 檢視解析器內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!