SpringBoot之Web開發基礎
回顧
開發步驟
① 建立SpringBoot應用, 選中所需的模組.
② 在配置檔案中進行少量的配置
③ 編寫業務邏輯程式碼
自動配置原理
xxxAutoConfiguration: 給容器自動配置元件
xxxProperties: 配置類封裝配置檔案的內容
SpringBoot對靜態資源的對映規則
進入WebMvcAutoConfiguration:
//可以設定和靜態資源有關的引數,快取時間等
public void addResourceHandlers(ResourceHandlerRegistry registry) { if (!this.resourceProperties.isAddMappings()) { logger.debug("Default resource handling disabled"); } else { Integer cachePeriod = this.resourceProperties.getCachePeriod(); if (!registry.hasMappingForPattern("/webjars/**
//靜態資原始檔夾對映 if (!registry.hasMappingForPattern(staticPathPattern)) { this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(this.resourceProperties.getStaticLocations()).setCachePeriod(cachePeriod)); } } }
//配置歡迎頁對映
@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(-2147483647); //所有 **/favicon.ico mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", this.faviconRequestHandler())); return mapping; } @Bean public ResourceHttpRequestHandler faviconRequestHandler() { ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler(); requestHandler.setLocations(this.resourceProperties.getFaviconLocations()); return requestHandler; } }
① 所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找資源
webjars:以jar包的方式引入靜態資源
例如, 引入jquery的webjar包的依賴
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
訪問路徑: localhost:8080/webjars/jquery/3.3.1/jquery.js
② "/**" 訪問當前專案的任何資源,都去(靜態資源的資料夾)找對映
"classpath:/META‐INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":當前專案的根路徑
localhost:8080/[靜態資原始檔名] ==> 去靜態資原始檔夾裡面找該檔案
③ 首頁(靜態資原始檔夾下的所有index.html頁面), 被"/**"對映
localhost:8080/ ==> 自動找index.html
④ 所有的 **/favicon.ico 都是在靜態資原始檔夾下找
網站圖示也在靜態資原始檔夾下找
模板引擎
模型圖:
SpringBoot推薦的模板引擎: thymeleaf
① 引入thymeleaf
<!--引入thymeleaf模板引擎-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--切換thymeleaf的版本-->
<properties>
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<!--如果thymeleaf的版本為thymeleaf3 則適配thymeleaf-layout-dialect2以上-->
<!--如果thymeleaf的版本為thymeleaf2 則適配thymeleaf-layout-dialect1以上-->
<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
</properties>
② thymeleaf的使用和語法
預設規則:
private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
public static final String DEFAULT_PREFIX = "classpath:/templates/"; //預設字首
public static final String DEFAULT_SUFFIX = ".html"; //預設字尾
所以, 只要把html頁面放在classpath:/templates/, thymeleaf就能自動渲染了.
1) 匯入thymeleaf的名稱空間
<html lang="en" xmlns:th="http://www.thymeleaf.org"></html>
2) 使用thymeleaf的語法
controller:
@RequestMapping("/success")
public String success(Map<String, Object> map){
map.put("hello", "你好, thymeleaf!");
//SpringBoot會在預設路徑下找classpath:/templates/success.html
return "success";
}
success.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>測試模板引擎thymeleaf3</title>
</head>
<body>
<h3>成功訪問...</h3>
<!--th:text 將div裡邊的為本內容設定為指定的值-->
<div th:text="${hello}"></div>
</body>
</html>
3) 語法規則
th:[任意html屬性] 改變當前屬性裡面的內容
如: th:text 改變當前元素裡面的文字內容
4) 表示式
Simple expressions(表示式語法)
Variable Expressions: ${...} OGNL表示式:
1. 獲取物件的屬性, 呼叫方法
2. 使用內建的基本物件: #ctx
#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
#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).
如: ${#strings.toString(obj)} ...
Selection Variable Expressions: *{...} 變數選擇表示式: 在功能上和${}是一樣的
補充功能:
<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>
等同於
<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>
相當於將${session.user}的值賦給th:object, 然後*代表th:object
Message Expressions: #{...} 獲取國際化內容的
Link URL Expressions: @{...} 定義url連結的
<a href="details.html" th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a> //標準寫法
@{/order/process(execId=${execId},execType='FAST')} //簡寫(並且可以傳多個引數)
Fragment Expressions: ~{...} 片段引用表示式
<div th:insert="~{commons :: main}">...</div>
<div th:with="frag=~{footer :: #main/text()}">
<p th:insert="${frag}">
</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: _
小測試:
@RequestMapping("/success")
public String success(Map<String, Object> map){
map.put("hello", "<h3>你好啊!!!</h3>");
map.put("users", Arrays.asList("zhangsan", "zhaoliu", "tianqi"));
//SpringBoot會在預設路徑下找classpath:/templates/success.html
return "success";
}
<div th:text="${hello}"></div>
<div th:utext="${hello}"></div>
<hr/>
<h3 th:each="user:${users}" th:text="${user}"></h3>
<h5>
<span th:each="user:${users}">[[${user}]]</span>
</h5>
關於SpringMVC的自動配置
SpringBoot對SpringMVC的預設配置:
● 自動配置了ViewResolver(檢視解析器: 根據方法的返回值得到檢視物件, 然後決定如何渲染(轉發? 重定向? ...))
● 組合所有的檢視解析器
● ViewResolver
○ 如何定製: 可以自己給容器中新增一個檢視解析器, 自動將其組合進來
● 靜態資原始檔夾 / webjars
● 靜態首頁訪問
● favicon.ico
● 自動註冊Converter(轉換器), Formatter(格式化器)
○ Converter: 型別轉換使用(頁面提交的資料都是文字, 需要轉換器將其轉換成各種型別的資料)
○ Formatter: 時間格式化使用(頁面提交的時間資料也是文字, 需要格式化器將其格式化成具體的時間資料)
@Bean
@ConditionalOnProperty(
prefix = "spring.mvc",
name = {"date-format"} //需要在配置檔案中配置日期格式化的規則
)
public Formatter<Date> dateFormatter() {
return new DateFormatter(this.mvcProperties.getDateFormat()); //日期格式化元件
}
○ 如何定製: 自己新增格式化器轉換器, 只需要放入容器中即可
● HttpMessageConverters
○ SpringMVC用來轉換http請求和響應的(物件 <==> JSON)
○ HttpMessageConverters需要從容器中確定, 獲取所有的HttpMessageConverter
○ 如何定製: 自己將其放入容器中即可
@Configuration
public class MyConfiguration {
@Bean
public HttpMessageConverters customConverters() {
HttpMessageConverter<?> additional = ...
HttpMessageConverter<?> another = ...
return new HttpMessageConverters(additional, another); //返回一個HttpMessageConverters物件即可
}
}
● MessageCodesResolver(定義錯誤程式碼生成規則)
● ConfigurableWebBindingInitializer
protected ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer() {
try {
return (ConfigurableWebBindingInitializer)this.beanFactory.getBean(ConfigurableWebBindingInitializer.class); //從容器中獲取
} catch (NoSuchBeanDefinitionException var2) { //如果容器中拿不到
return super.getConfigurableWebBindingInitializer(); //呼叫父類的方法
}
}
protected ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer() { //父類的方法
ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
initializer.setConversionService(this.mvcConversionService());
initializer.setValidator(this.mvcValidator());
initializer.setMessageCodesResolver(this.getMessageCodesResolver());
return initializer;
}
ConfigurableWebBindingInitializer :
public void initBinder(WebDataBinder binder, WebRequest request) { //初始化WebDataBinder
binder.setAutoGrowNestedPaths(this.autoGrowNestedPaths);
if (this.directFieldAccess) {
binder.initDirectFieldAccess();
}
if (this.messageCodesResolver != null) {
binder.setMessageCodesResolver(this.messageCodesResolver);
}
if (this.bindingErrorProcessor != null) {
binder.setBindingErrorProcessor(this.bindingErrorProcessor);
}
if (this.validator != null && binder.getTarget() != null && this.validator.supports(binder.getTarget().getClass())) {
binder.setValidator(this.validator);
}
if (this.conversionService != null) {
binder.setConversionService(this.conversionService);
}
if (this.propertyEditorRegistrars != null) {
PropertyEditorRegistrar[] var3 = this.propertyEditorRegistrars;
int var4 = var3.length;
for(int var5 = 0; var5 < var4; ++var5) {
PropertyEditorRegistrar propertyEditorRegistrar = var3[var5];
propertyEditorRegistrar.registerCustomEditors(binder);
}
}
}
○ 初始化Web資料繫結器(WebDataBinder)
○ 返回的資料跟物件的繫結
○ 如何定製: 自己將元件新增進容器即可(其本身就是在容器中獲取的)
擴充套件SpringMVC的配置:
配置檔案:
<mvc:view‐controller path="/hello" view‐name="success"/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/hello"/>
<bean></bean>
</mvc:interceptor>
</mvc:interceptors>
編寫一個配置類(@Configuration), 是WebMvcConfigurerAdapter型別, 但不能標註@EnableWebMvc.
//使用WebMvcConfigurerAdapter可以來擴充套件SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//瀏覽器傳送 /testSuccess 請求來到 success
registry.addViewController("/testSuccess").setViewName("success");
}
}
原理:
① WebMvcAutoConfiguration是SpringMVC的自動配置類
② 在做其他自動配置時會匯入;@Import(EnableWebMvcConfiguration.class)
③ 容器中所有的WebMvcConfigurer都會一起起作用
④ 自己定義的配置類也會起作用
全面接管SpringMVC:
只需要自己配置, 無需SpringBoot對SpringMVC的自動配置, 只需要在配置類上新增@EnableWebMvc即可
@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//瀏覽器傳送 /testSuccess 請求來到 success
registry.addViewController("/testSuccess").setViewName("success");
}
}
原理:
① @EnableWebMvc的核心
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
②
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
③
@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
WebMvcConfigurerAdapter.class })
//容器中沒有這個元件的時候,這個自動配置類才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {
④ @EnableWebMvc將WebMvcConfigurationSupport元件匯入進來
⑤ 所以, SpringBoot對SpringMVC的自動配置失效
如何修改SpringBoot的預設配置
模式:
① SpringBoot在自動配置很多元件的時候,先看容器中有沒有使用者配置的(@Bean、@Component), 如果有就用使用者配置的,如果沒有,才自動配置;如果有些元件可以有多個(如: ViewResolver), 則將使用者配置的和自動配置的組合起來.
② 在SpringBoot中會有非常多的xxxConfigurer幫助我們進行擴充套件配置.