SpringBoot應用配置常用相關檢視解析器
目錄
- SpringBoot的自動裝配裝配了檢視解析器了嗎?
- SpringBoot中使用Thymeleaf
- SpringBoot中使用Freemark
SpringBoot的自動裝配裝配了檢視解析器了嗎?
我們可以看到SpringBoot自動裝配的 WebMvcAutoConfiguration
類中,裝配了以下關於 ViewResolver
(檢視解析器)的類。可以看到SpringBoot已經自動裝配了 InternalResourceViewResolver
類,又是通過 外部資源配置
的方式來配置此檢視解析器 this.mvcProperties.getView().getPrefix()
,所以我們可以在 application.properties
檔案配置此檢視解析器用於解析JSP。
@Bean @ConditionalOnMissingBean public InternalResourceViewResolver defaultViewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix(this.mvcProperties.getView().getPrefix()); resolver.setSuffix(this.mvcProperties.getView().getSuffix()); return resolver; }
SpringBoot使用JSP
SpringBoot在自動裝配的時候預設就已經將JSP的檢視解析器 InternalResourceViewResolver
裝配。所以我們只需要進行配置使用即可。在SpringBoot中使用JSP比較麻煩一點,或許是我的個人理解存在什麼誤區,如果有朋友知道更好的配置方法,請留言給我。
第一步:建立自定義webapp目錄,如下所示
第二步:將此資料夾配置成專案的WEB模組
第三步:匯入JSP相關依賴
<dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency>
第四步:在SpringBoot的屬性檔案 application.properties
中配置JSP的路由
spring.mvc.view.prefix=/ spring.mvc.view.suffix=.jsp
第五步:修改Maven的pom.xml檔案打包方式改成war(預設打包Jar,打包Jar包的方式使用Idea啟動是沒什麼問題,如果單獨執行Jar包就找不到JSP檔案,如果改成War包即可)
<packaging>war</packaging>
SpringBoot中使用Thymeleaf
SpringBoot官方是推薦使用thymeleaf作為優選的檢視解析器,所以SpringBoot對Thymeleaf的支援非常好,這裡僅僅演示SpringBoot如何選用Thymeleaf作用預設檢視解析器。
第一步:匯入Thymeleaf的依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
第二步:建立存放Thymeleaf模板資料夾,在Resources目錄下建立templates目錄
這個資料夾的名字可不是我麼隨便命名的啊,是SpringBoot在自動裝配Thymeleaf檢視解析器的時候就已經預定義好了,我們看一下它的定義原始碼。
@ConfigurationProperties(prefix = "spring.thymeleaf") public class ThymeleafProperties { private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html"; }
SpringBoot中使用Freemark
第一步:匯入Maven依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
第二步:建立存放Freemark模板資料夾,在Resources目錄下建立templates目錄
@ConfigurationProperties(prefix = "spring.freemarker") public class FreeMarkerProperties extends AbstractTemplateViewResolverProperties { public static final String DEFAULT_TEMPLATE_LOADER_PATH = "classpath:/templates/"; public static final String DEFAULT_PREFIX = ""; public static final String DEFAULT_SUFFIX = ".ftl"; }
我們可以看到SpringBoot在自動裝配Freemarker檢視解析器預設是將模板檔案放在classpath:/templates/路徑內,我們同樣可以在SpringBoot的配置檔案中自行配置。
小提示:我在寫Freemark檢視解析器的時候並沒有將第一個JSP內部資源解析器給刪除掉,所以他們是並存的,所以我們可以知道SpringBoot在裝配他們的時候給予設定了優先順序順序。從下圖可以看到他們的優先順序順序;Freemarker >
Thymeleaf >
InternalResourceViewResolver`
該教程所屬Java工程師之SpringBoot系列教程,本系列相關博文目錄 ofollow,noindex" target="_blank">Java工程師之SpringBoot系列教程前言&目錄