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系列教程,本系列相關博文目錄 Java工程師之SpringBoot系列教程前言&目錄