自動配置原理html
這個場景Springboot幫咱們配置了什麼、能不能修改呢?能修改哪些配置?java
xxxxxAutoConfiguration :幫咱們給容器自動配置組件jquery
xxxproperties 配置類來封裝配置文件的內容web
@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false) public class ResourceProperties implements ResourceLoaderAware { //能夠設置和靜態資源有關的參數,緩存時間等 } //webMVC的自動配置 WebMvcAuotConfiguration: @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); return; } Integer cachePeriod = this.resourceProperties.getCachePeriod(); if (!registry.hasMappingForPattern("/webjars/**")) { customizeResourceHandlerRegistration( registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/").setCachePeriod(cachePeriod)); } String staticPathPattern = this.mvcProperties.getStaticPathPattern(); //靜態資源文件夾映射 if (!registry.hasMappingForPattern(staticPathPattern)) { customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern).addResourceLocations(this.resourceProperties.getStaticLocations()).setCachePeriod(cachePeriod)); } } //配置歡迎頁映射 @Bean public WelcomePageHandlerMapping welcomePageHandlerMapping(ResourceProperties resourceProperties) { return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(), this.mvcProperties.getStaticPathPattern()); } //配置喜歡的圖標 即咱們網頁標籤最左邊的圖標 @Configuration @ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true) public static class FaviconConfiguration { private final ResourceProperties resourceProperties; public FaviconConfiguration(ResourceProperties resourceProperties) {this.resourceProperties = resourceProperties; } @Bean public SimpleUrlHandlerMapping faviconHandlerMapping() { SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1); //全部 **/favicon.ico mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",faviconRequestHandler())); return mapping; } @Bean public ResourceHttpRequestHandler faviconRequestHandler() { ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler(); requestHandler.setLocations(this.resourceProperties.getFaviconLocations()); return requestHandler; } }
pom.xml 依賴:spring
<!--引入jquery-webjar-->在訪問的時候只須要寫webjars下面資源的名稱便可 <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.3.1</version> </dependency>
訪問地址:localhost:8080/webjars/jquery/3.3.1/jquery.jsexpress
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":當前項目的根路徑
localhost:8080/abc === 默認去靜態資源文件夾裏面找abcapi
經常使用的模板引擎有:JSP,Velocity、Freemarker、Thymeleaf緩存
Springboot 推薦使用thymeleaf ,語法更簡單,功能更強大。springboot
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> SpringBoot默認的thymeleaf 版本爲 2.1.6 ,該版本過低,因此咱們須要手動切換thymeleaf版本 <properties> <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version> <!-- 佈局功能的支持程序 thymeleaf3主程序 layout2以上版本 --> <!-- thymeleaf2 layout1--> <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version> </properties>
SpringBoot 的其餘默認版本的依賴也是這樣切換,若是須要修改的話,同樣的切換思路。
配置上面這兩個的時候,啓動Springboot 會報錯誤session
An attempt was made to call the method org.thymeleaf.spring5.SpringTemplateEngine.setRenderHiddenMarkersBeforeCheckboxes(Z)V but it does not exist. Its class, org.thymeleaf.spring5.SpringTemplateEngine, is available from the following locations:
jar:file:/E:/springboot/repository/org/thymeleaf/thymeleaf-spring5/3.0.9.RELEASE/thymeleaf-spring5-3.0.9.RELEASE.jar!/org/thymeleaf/spring5/SpringTemplateEngine.class
It was loaded from the following location:
file:/E:/springboot/repository/org/thymeleaf/thymeleaf-spring5/3.0.9.RELEASE/thymeleaf-spring5-3.0.9.RELEASE.jar
Action:
Correct the classpath of your application so that it contains a single, compatible version of org.thymeleaf.spring5.SpringTemplateEngine
修改成如下便可:
配置:
@ConfigurationProperties(prefix = "spring.thymeleaf") public class ThymeleafProperties { private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8"); private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
//只要咱們把HTML頁面放在classpath:/templates/,thymeleaf就能自動渲染;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
使用:
1,在html 頁面上導入thymeleaf的命名空間 , 不導入也能夠,只是在寫代碼的時候,沒有相應的代碼提示。
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>成功!</h1> <!--th:text 將div裏面的文本內容設置爲 --> <div th:text="${hello}">這是顯示歡迎信息</div> </body> </html>
1)、th:text;改變當前元素裏面的文本內容;
2)、表達式
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. ${session.foo} 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> Message Expressions: #{...}:獲取國際化內容 Link URL Expressions: @{...}:定義URL; @{/order/process(execId=${execId},execType='FAST')} Fragment Expressions: ~{...}:片斷引用表達式 <div th:insert="~{commons :: main}">...</div> 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: _