模板引擎Thymeleaf,SpringMVC自動配置,修改SpringBoot默認配置、RestfulCRUD
Web開發
1、模板引擎 Thymeleaf
JSP、Velocity、Freemarker、Thymeleaf
1、引入thymeleaf;
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
2.1.6
</dependency>
切換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>
2、Thymeleaf使用
@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");
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">
2、使用thymeleaf語法;
<!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>
3、語法規則
1)、th:text;改變當前元素裏面的文本內容;
th:任意html屬性;來替換原生屬性的值
2)、表達式 官方文檔。
Simple expressions:(表達式語法)
1、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).
2、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>
3、Message Expressions: #{...}:獲取國際化內容
4、Link URL Expressions: @{...}:定義URL;
@{/order/process(execId=${execId},execType='FAST')}
5、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: _
2、SpringMVC自動配置
https://docs.spring.io/spring-boot/docs/1.5.10.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications
1. Spring MVC auto-configuration
Spring Boot 自動配置好了SpringMVC
以下是SpringBoot對SpringMVC的默認配置:(WebMvcAutoConfiguration)
-
Inclusion of
ContentNegotiatingViewResolver
andBeanNameViewResolver
beans.- 自動配置了ViewResolver(視圖解析器:根據方法的返回值得到視圖對象(View),視圖對象決定如何渲染(轉發?重定向?))
- ContentNegotiatingViewResolver:組合所有的視圖解析器的;
- 如何定製:我們可以自己給容器中添加一個視圖解析器;自動的將其組合進來;
-
Support for serving static resources, including support for WebJars (see below).靜態資源文件夾路徑,webjars
-
Static
index.html
support. 靜態首頁訪問 -
Custom
Favicon
support (see below). favicon.ico -
自動註冊了 of
Converter
,GenericConverter
,Formatter
beans.- Converter:轉換器; public String hello(User user):類型轉換使用Converter
Formatter
格式化器; 2017.12.17===Date;
@Bean
@ConditionalOnProperty(prefix = "spring.mvc", name = "date-format")//在文件中配置日期格式化的規則
public Formatter<Date> dateFormatter() {
return new DateFormatter(this.mvcProperties.getDateFormat());//日期格式化組件
}
**自己添加的格式化器轉換器,我們只需要放在容器中即可**
-
Support for
HttpMessageConverters
(see below).-
HttpMessageConverter:SpringMVC用來轉換Http請求和響應的;User—Json;
-
HttpMessageConverters
是從容器中確定;獲取所有的HttpMessageConverter;自己給容器中添加HttpMessageConverter,只需要將自己的組件註冊容器中(@Bean,@Component)
-
-
Automatic registration of
MessageCodesResolver
(see below).定義錯誤代碼生成規則 -
Automatic use of a
ConfigurableWebBindingInitializer
bean (see below).我們可以配置一個ConfigurableWebBindingInitializer來替換默認的;(添加到容器)
初始化WebDataBinder; 請求數據=====JavaBean;
org.springframework.boot.autoconfigure.web:web的所有自動場景;
If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.) you can add your own @Configuration
class of type WebMvcConfigurerAdapter
, but without @EnableWebMvc
. If you wish to provide custom instances of RequestMappingHandlerMapping
, RequestMappingHandlerAdapter
or ExceptionHandlerExceptionResolver
you can declare a WebMvcRegistrationsAdapter
instance providing such components.
If you want to take complete control of Spring MVC, you can add your own @Configuration
annotated with @EnableWebMvc
.
2、擴展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);
//瀏覽器發送 /atguigu 請求來到 success
registry.addViewController("/atguigu").setViewName("success");
}
}
原理:
1)、WebMvcAutoConfiguration是SpringMVC的自動配置類
2)、在做其他自動配置時會導入;@Import(**EnableWebMvcConfiguration**.class)
@Configuration
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {
private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
//從容器中獲取所有的WebMvcConfigurer
@Autowired(required = false)
public void setConfigurers(List<WebMvcConfigurer> configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
//一個參考實現;將所有的WebMvcConfigurer相關配置都來一起調用;
@Override
// public void addViewControllers(ViewControllerRegistry registry) {
// for (WebMvcConfigurer delegate : this.delegates) {
// delegate.addViewControllers(registry);
// }
}
}
}
3)、容器中所有的WebMvcConfigurer都會一起起作用;
4)、我們的配置類也會被調用;
效果:SpringMVC的自動配置和我們的擴展配置都會起作用;
3、全面接管SpringMVC;
SpringBoot對SpringMVC的自動配置不需要了,所有都是我們自己配置;所有的SpringMVC的自動配置都失效了
我們需要在配置類中添加@EnableWebMvc即可;
//使用WebMvcConfigurerAdapter可以來擴展SpringMVC的功能
@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//瀏覽器發送 /atguigu 請求來到 success
registry.addViewController("/atguigu").setViewName("success");
}
}
原理:
爲什麼@EnableWebMvc自動配置就失效了;
1)@EnableWebMvc的核心
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
2)、
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
3)、
@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 {
4)、@EnableWebMvc將WebMvcConfigurationSupport組件導入進來;
5)、導入的WebMvcConfigurationSupport只是SpringMVC最基本的功能;
3、如何修改SpringBoot的默認配置
模式:
1)、SpringBoot在自動配置很多組件的時候,先看容器中有沒有用戶自己配置的(@Bean、@Component)如果有就用用戶配置的,如果沒有,才自動配置;如果有些組件可以有多個(ViewResolver)將用戶配置的和自己默認的組合起來;
2)、在SpringBoot中會有非常多的xxxConfigurer幫助我們進行擴展配置
3)、在SpringBoot中會有很多的xxxCustomizer幫助我們進行定製配置
4、RestfulCRUD
1)、默認訪問首頁
//使用WebMvcConfigurerAdapter可以來擴展SpringMVC的功能
//@EnableWebMvc 不要接管SpringMVC
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//瀏覽器發送 /atguigu 請求來到 success
registry.addViewController("/atguigu").setViewName("success");
}
@Configuration
public class WebMvcConfg implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index").setViewName("index");
registry.addViewController("/").setViewName("index");
}
}
}
2)、國際化
springMVC的步驟:
1)、編寫國際化配置文件;
2)、使用ResourceBundleMessageSource管理國際化資源文件
3)、在頁面使用fmt:message取出國際化內容
步驟:
1、編寫國際化配置文件,抽取頁面需要顯示的國際化消息。
2、SpringBoot自動配置好了管理國際化資源文件的組件;
@ConfigurationProperties(prefix = "spring.messages")
public class MessageSourceAutoConfiguration {
/**
* Comma-separated list of basenames (essentially a fully-qualified classpath
* location), each following the ResourceBundle convention with relaxed support for
* slash based locations. If it doesn't contain a package qualifier (such as
* "org.mypackage"), it will be resolved from the classpath root.
*/
private String basename = "messages";
//我們的配置文件可以直接放在類路徑下叫messages.properties;
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
if (StringUtils.hasText(this.basename)) {
//設置國際化資源文件的基礎名(去掉語言國家代碼的)
messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
StringUtils.trimAllWhitespace(this.basename)));
}
if (this.encoding != null) {
messageSource.setDefaultEncoding(this.encoding.name());
}
messageSource.setFallbackToSystemLocale(this.fallbackToSystemLocale);
messageSource.setCacheSeconds(this.cacheSeconds);
messageSource.setAlwaysUseMessageFormat(this.alwaysUseMessageFormat);
return messageSource;
}
在這裏例子中就是
spring.messages.basename=il8n.index
3、去頁面獲取國際化的值;
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Signin Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="asserts/css/signin.css" th:href="@{/asserts/css/signin.css}" rel="stylesheet">
</head>
<body class="text-center">
<form class="form-signin" action="dashboard.html">
<img class="mb-4" th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" alt="" width="72" height="72">
<h1 class="h3 mb-3 font-weight-normal" th:text="#{login.tip}">Please sign in</h1>
<label class="sr-only" th:text="#{login.username}">Username</label>
<input type="text" class="form-control" placeholder="Username" th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" class="form-control" placeholder="Password" th:placeholder="#{login.password}" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"/> [[#{login.remember}]]
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit" th:text="#{login.btn}">Sign in</button>
<p class="mt-5 mb-3 text-muted">© 2017-2018</p>
<a class="btn btn-sm">中文</a>
<a class="btn btn-sm">English</a>
</form>
</body>
</html>
效果:根據瀏覽器語言設置的信息切換了國際化;
當瀏覽器爲中文時:
當瀏覽器爲英文時
點擊切換語言按鈕切換原理:
國際化Locale(區域信息對象);LocaleResolver(獲取區域信息對象);
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(prefix = "spring.mvc", name = "locale")
public LocaleResolver localeResolver() {
if (this.mvcProperties
.getLocaleResolver() == WebMvcProperties.LocaleResolver.FIXED) {
return new FixedLocaleResolver(this.mvcProperties.getLocale());
}
AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
localeResolver.setDefaultLocale(this.mvcProperties.getLocale());
return localeResolver;
}
默認的就是根據請求頭帶來的區域信息獲取Locale進行國際化
4、點擊鏈接切換國際化
/**
* 可以在連接上攜帶區域信息
*/
public class MyLocaleResolver implements LocaleResolver {
@Override
public Locale resolveLocale(HttpServletRequest request) {
String l = request.getParameter("l");
Locale locale = Locale.getDefault();
if(!StringUtils.isEmpty(l)){
String[] split = l.split("_");
locale = new Locale(split[0],split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
然後將其加到容器中
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
}