XxxAutoConfiguration:幫咱們給容器中自動配置組件 XxxProperties:配置類,封裝配置文件中的內容
@ConfigurationProperties( prefix = "spring.resources", ignoreUnknownFields = false )
/* * ResourceHandlerRegistry存儲用於經過Spring MVC服務靜態資源的資源處理程序的註冊 * 容許設置爲在Web瀏覽器中高效加載而優化的緩存頭 * 能夠在Web應用的目錄下,類路徑等位置以外的位置提供資源 */ public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); } else { Duration cachePeriod = this.resourceProperties.getCache().getPeriod(); CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl(); if (!registry.hasMappingForPattern("/webjars/**")) { this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern(); if (!registry.hasMappingForPattern(staticPathPattern)) { this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl)); } } }
/**:訪問當前項目的任何資源(靜態資源的文件夾)html
classpath:/META-INF/resources/ classpath:/resources/ classpath:/static/ classpath:/public/ / # 當前項目的根路徑
@Bean public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext) { return new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern()); }
配置歡迎頁的映射:java
@Configuration @ConditionalOnProperty( value = {"spring.mvc.favicon.enabled"}, matchIfMissing = true ) /* * ResourceLoaderAware是一個標記接口 * 用於經過ApplicationContext上下文注入ResourceLoader * 有setResourceLoader()方法 */ public static class FaviconConfiguration implements ResourceLoaderAware { private final ResourceProperties resourceProperties; /* * ResourceLoader用於返回Resource對象和ClassLoader對象 * - getResource(String location)方法根據提供的location參數返回相應的Resource對象 * - getClassLoader()方法則返回加載這些Resource的ClassLoader */ private ResourceLoader resourceLoader; public FaviconConfiguration(ResourceProperties resourceProperties) { this.resourceProperties = resourceProperties; } public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } /* * SimpleUrlHandlerMapping是SpringMVC中適應性最強的Handler Mapping類 * 容許明確指定URL模式和Handler的映射關係.有兩種聲明方式: * - prop: * - key: URL模式 * — value: Handler的ID或者名字 * - value: * - 等號左邊是URL模式 * - 等號右邊是HandlerID或者名字 */ @Bean public SimpleUrlHandlerMapping faviconHandlerMapping() { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(-2147483647); mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler())); return mapping; }
配置喜歡的圖標(標籤的圖標):web
優勢 | 缺點 | |
---|---|---|
jsp | 1. 功能強大,能夠寫Java代碼 2. 支持jsp標籤 - jsp tag 3. 支持表達式語言 - EL表達式 4. 官方標準,使用普遍,豐富的第三方jsp標籤庫 5. 性能良好 ,jsp編譯成class文件執行,有很好的性能表現 |
1. jsp沒有明顯的缺點 2. 因爲能夠編寫Java代碼,使用不當容易破壞MVC結構 |
velocity | 1. 不編寫Java代碼,實現嚴格的MVC分離 2. 性能良好,比jsp優越 3. 使用表達式語言 - EL表達式 |
1. 不是官方標準 2. 使用範圍小,第三方標籤庫較少 3. 對jsp標籤的支持不夠友好 |
freemarker | 1. 不編寫Java代碼,實現嚴格的MVC分離 2. 性能很是好 3. 對jsp標籤支持良好 4. 內置大量經常使用功能,使用很是方便 5. 宏定義(相似jsp標籤)很是方便 6. 使用表達式語言 - EL表達式 |
1.不是官方標準 2. 使用範圍小,第三方標籤庫較少 |
thymeleaf | 1. 靜態html嵌入標籤屬性,瀏覽器能夠直接打開模板文件,便於後端聯調 2. SpringBoot框架推薦模板 |
1.模板必須符合xml規範 2. 須要加入js腳本 |
<properties> <!-- 切換thymeleaf版本 --> <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version> <!-- 佈局功能支持程序-thymeleaf3==layout2 thymeleaf2==layout1 --> <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version> </properties> <dependency> <!-- 引入thymeleaf依賴 --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
@ConfigurationProperties( prefix = "spring.thymeleaf" ) public class ThymeleafProperties { private static final Charset DEFAULT_ENCODING; public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html"; private boolean checkTemplate = true; private boolean checkTemplateLocation = true; private String prefix = "classpath:/templates/"; private String suffix = ".html"; private String mode = "HTML"; private Charset encoding;
<html xmlns:th="http://www.thymeleaf.org">
2.使用thymeleaf語法:spring
thymeleaf | jsp | |
---|---|---|
片斷包含 | th:insert th:replace |
include |
遍歷 | th:each | c:forEach |
條件判斷 | th:if th:unless th:switch th:case |
c:if |
聲明變量 | th:object th:with |
c:set |
任意屬性修改 | th:attr th:attrprepend(前面) th:attrappend(後面) |
|
修改指定屬性默認值 | th:value th:href th:src |
|
修改標籤體文本內容 | th:text(轉義) th:utext(不轉義) |
|
聲明片斷 | th:fragment | |
移除聲明片斷 | th:remove |
Simple expressions: (表達式語法) Variable Expressions: ${...} (獲取變量值-OGNL) 1.獲取對象的屬性,調用方法 2.使用內置的基本對象: #ctx : the context object. #vars: the context variables. #locale : the context locale. #request : (only in Web Contexts) the HttpServletRequest object. #response : (only in Web Contexts) the HttpServletResponse object. #session : (only in Web Contexts) the HttpSession object. #servletContext : (only in Web Contexts) the ServletContext object. 3.內置的工具對象: #execInfo : information about the template being processed. #messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax. #uris : methods for escaping parts of URLs/URIs #conversions : methods for executing the configured conversion service (if any). #dates : methods for java.util.Date objects: formatting, component extraction, etc. #calendars : analogous to #dates , but for java.util.Calendar objects. #numbers : methods for formatting numeric objects. #strings : methods for String objects: contains, startsWith, prepending/appending, etc. #objects : methods for objects in general. #bools : methods for boolean evaluation. #arrays : methods for arrays. #lists : methods for lists. #sets : methods for sets. #maps : methods for maps. #aggregates : methods for creating aggregates on arrays or collections. #ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration). Selection Variable Expressions: *{...} (選擇表達式,和${}在用法上大致一致) 補充:配合th:object="${session.user}" <div th:object="${session.user}"> <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p> <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p> <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p> </div> Which is exactly equivalent to: <div> <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p> <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p> <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p> </div> Message Expressions: #{...} (獲取國際化內容) Link URL Expressions: @{...} (定義url) <a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a> <!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) --> <a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a> <!-- Will produce '/gtvg/order/3/details' (plus rewriting) --> <a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a> Fragment Expressions: ~{...} (片斷引用表達式) Literals(字面量) Text literals: 'one text' , 'Another one!' ,… Number literals: 0 , 34 , 3.0 , 12.3 ,… Boolean literals: true , false Null literal: null Literal tokens: one , sometext , main ,… Text operations (文本操做) String concatenation: + Literal substitutions: |The name is ${name}| Arithmetic operations (數學運算) Binary operators: + , - , * , / , % Minus sign (unary operator): - Boolean operations (布爾運算) Binary operators: and , or Boolean negation (unary operator): ! , not Comparisons and equality (比較運算) Comparators: > , < , >= , <= ( gt , lt , ge , le ) Equality operators: == , != ( eq , ne ) Conditional operators(條件運算) If-then: (if) ? (then) If-then-else: (if) ? (then) : (else) Default: (value) ?: (defaultvalue) Special tokens(特殊操做) No-Operation: _
@Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class})
EnableWebMvcConfiguration:數據庫
@Configuration public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {
DelegatingWebMvcConfiguration:express
// @Autowired( required = false ) public void setConfigurers(List<WebMvcConfigurer> configurers) { if (!CollectionUtils.isEmpty(configurers)) { this.configurers.addWebMvcConfigurers(configurers); } }
參考實現:後端
//將全部的WebMvcConfigurer相關的配置都調用一遍 public void addViewControllers(ViewControllerRegistry registry) { Iterator var2 = this.delegates.iterator(); while(var2.hasNext()) { WebMvcConfigurer delegate = (WebMvcConfigurer)var2.next(); delegate.addViewControllers(registry); } }
@Import({DelegatingWebMvcConfiguration.class}) public @interface EnableWebMvc { }
DelegatingWebMvcConfiguration:api
@Configuration public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
WebMvcAutoConfiguration:數組
@Configuration @ConditionalOnWebApplication( type = Type.SERVLET ) @ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class}) @ConditionalOnMissingBean({WebMvcConfigurationSupport.class}) //當容器中沒有此組件時,此自動配置類才生效 @AutoConfigureOrder(-2147483638) @AutoConfigureAfter({DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class})