1、简介

如果使用SpringBoot;

1)、创建SpringBoot应用,选中我们需要的模块;

2)、SpringBoot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来

3)、自己编写业务代码;

自动配置原理:

xxxxAutoConfiguration:帮我们给容器中自动配置组件;
xxxxProperties:配置类来封装配置文件的内容;

2、静态资源的映射规则

在ResourceProperties配置文件类中

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties { private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/" }; /**
* Locations of static resources. Defaults to classpath:[/META-INF/resources/,
* /resources/, /static/, /public/].
*/
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
.....

可以看到静态资源的位置。

WebMvcAuotConfiguration自动配置类

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
//静态资源文件夹映射
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if (!registry.hasMappingForPattern(staticPathPattern)) {
customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}
} //配置图标
@Configuration
@ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
public static class FaviconConfiguration implements ResourceLoaderAware { private final ResourceProperties resourceProperties; private ResourceLoader resourceLoader; public FaviconConfiguration(ResourceProperties resourceProperties) {
this.resourceProperties = resourceProperties;
} @Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
} @Bean
public SimpleUrlHandlerMapping faviconHandlerMapping() {
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", faviconRequestHandler()));
return mapping;
} @Bean
public ResourceHttpRequestHandler faviconRequestHandler() {
ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
requestHandler.setLocations(resolveFaviconLocations());
return requestHandler;
} private List<Resource> resolveFaviconLocations() {
String[] staticLocations = getResourceLocations(this.resourceProperties.getStaticLocations());
List<Resource> locations = new ArrayList<>(staticLocations.length + 1);
Arrays.stream(staticLocations).map(this.resourceLoader::getResource).forEach(locations::add);
locations.add(new ClassPathResource("/"));
return Collections.unmodifiableList(locations);
} } }
//配置欢迎页的映射
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext) {
WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
this.mvcProperties.getStaticPathPattern());
welcomePageHandlerMapping.setInterceptors(getInterceptors());
return welcomePageHandlerMapping;
}

注意:

1)、所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找资源;

webjars:以jar包的方式引入静态资源;

访问方式:localhost:8080/webjars/jquery/3.4.1/jquery.js

<!--引入jquery-webjar-->在访问的时候只需要写webjars下面资源的名称即可
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.1</version>
</dependency>
			String staticPathPattern = this.mvcProperties.getStaticPathPattern();
/**

2)、"/**" 访问当前项目的任何资源,都去(静态资源的文件夹)找映射

"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/"
"/":当前项目的根路径

localhost:8080/abc === 去静态资源文件夹里面找abc

3、模板引擎

​ Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。



SpringBoot推荐的Thymeleaf,语法更简单,功能更强大;

1、引入thymeleaf

<!--引入thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
切换thymeleaf版本
<properties>
<java.version>1.8</java.version>
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 -->
<!-- thymeleaf2 layout1-->
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>

2、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";

只要我们把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属性;来替换原生属性的值

常用表达式:

${...}  变量表达式
*{...} 选择表达式
#{...} 消息文字表达式
@{...} 链接url表达式
#maps 工具对象表达式

常用标签:

th:action  定义后台控制器路径
th:each 循环语句
th:field 表单字段绑定
th:href 定义超链接
th:id div标签中的id声明,类似html标签中的id属性
th:if 条件判断语句
th:include 布局标签,替换内容到引入文件
th:fragment 布局标签,定义一个代码片段,方便其它地方引用
th:object 替换对象
th:src 图片类地址引入
th:text 显示文本
th:value 属性赋值
常用函数:
#dates 日期函数
#lists 列表函数
#arrays 数组函数
#strings 字符串函数
#numbers 数字函数
#calendars 日历函数
#objects 对象函数
#bools 逻辑函数

同时我们还需要在application.properties文件中添加Thymeleaf配置,具体代码如下:

#thymeleaf配置
#模板的模式,支持如:HTML、XML、TEXT、JAVASCRIPT等
spring.thymeleaf.mode=HTML5
#编码,可不用配置
spring.thymeleaf.encoding=UTF-8
#内容类别,可不用配置
spring.thymeleaf.content-type=text/html
#开发配置为false,避免修改模板还要重启服务器
spring.thymeleaf.cache=false
#配置模板路径,默认就是templates,可不用配置
#spring.thymeleaf.prefix=classpath:/templates/

注意:Thymeleaf模板引擎默认会读取my-spring-boot项目下的资源文件夹resource下的templates目录,这个目录是用来存放HTML文件的。如果我们添加了Thymeleaf依赖,而没有进行任何配置,或者添加默认目录,启动应用时就会报错。

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: _

4_1.springboot2.xWeb开发使用thymeleaf的更多相关文章

  1. 4_6.springboot2.xWeb开发之错误处理机制

    1.SpringBoot默认的错误处理机制 默认效果:1).浏览器,返回一个默认的错误页面 浏览器发送请求的请求头: ​ 2).如果是其他客户端,默认响应一个json数据 原理: ​ 默认情况下,Sp ...

  2. SpringBoot Web开发(4) Thymeleaf模板与freemaker

    SpringBoot Web开发(4) Thymeleaf模板与freemaker 一.模板引擎 常用得模板引擎有JSP.Velocity.Freemarker.Thymeleaf SpringBoo ...

  3. SpringBoot2.x开发案例之整合Quartz任务管理系统

    基于spring-boot 2.x + quartz 的CRUD任务管理系统,适用于中小项目. 基于spring-boot +quartz 的CRUD任务管理系统: https://gitee.com ...

  4. Spring Boot Web开发中Thymeleaf模板引擎的使用

    这里使用的是idea 1.新建Spring Boot项目 File-->New-->Project...,然后选择左边的Spring Initializr-->Next,可根据自己的 ...

  5. Spring Boot Web开发与thymeleaf模板引擎

    简介: 使用Springboot应用,选中需要的模块, Spring已经默认将场景配置好了,只需在配置文件中少量配置就可以运行起来 自己编写业务代码 自动配置原理 这个场景Springboot帮我们配 ...

  6. 零基础快速入门SpringBoot2.0教程 (三)

    一.SpringBoot Starter讲解 简介:介绍什么是SpringBoot Starter和主要作用 1.官网地址:https://docs.spring.io/spring-boot/doc ...

  7. [转]小D课堂 - 零基础入门SpringBoot2.X到实战_汇总

    原文地址:https://www.cnblogs.com/wangjunwei/p/11392825.html 第1节零基础快速入门SpringBoot2.0 小D课堂 - 零基础入门SpringBo ...

  8. 小D课堂 - 零基础入门SpringBoot2.X到实战_汇总

    第1节零基础快速入门SpringBoot2.0 小D课堂 - 零基础入门SpringBoot2.X到实战_第1节零基础快速入门SpringBoot2.0_1.SpringBoot2.x课程介绍和高手系 ...

  9. SpringBoot整合Thymeleaf-基于SpringBoot2.X版本

    1.为啥要用Thymeleaf模板引擎?现在不都前后端分离了么? 熊dei们,别着急,我们先来谈谈为啥开始用Thymeleaf模板引擎,先照顾照顾下我们这些可爱的小白童鞋.... 为啥开始用Thyme ...

随机推荐

  1. leetcode-第11场双周赛-5088-等差数列中缺失的数字

    题目描述: 自己的提交: class Solution: def missingNumber(self, arr: List[int]) -> int: if len(arr) == 2: re ...

  2. Java获取properties配置文件信息

    调用方法:String url = PropertiesUtil.getProperty("url"); public class PropertiesUtil { public ...

  3. 帝国cms把文章加入到收藏夹代码

    内容模板加这个:<a href="[!--news.url--]e/member/fava/add/?classid=[!--classid--]&id=[!--id--]&q ...

  4. css清除浮动的几种方法

    推荐几种好用的清除浮动方法: 方法1: .clearfix:after { content:"."; display:block; height:; clear:both; vis ...

  5. NX二次开发-UFUN获取边的端点UF_MODL_ask_edge_verts

    NX9+VS2012 #include <uf.h> #include <uf_modl.h> #include <uf_ui.h> #include <uf ...

  6. [kuangbin带你飞]专题一 简单搜索 - L - Oil Deposits

    #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #i ...

  7. 20140312 Excel表格画折现图次坐标轴

    1.struct 是8字节对齐 2.char * a, sizeof(a)=4; char a[]="abcdefg";sizeof(a)=8; 3.内存对其齐

  8. centos 7 ifcnfig提示:bash: ifconfig: command not found的解决方法

    接着上一篇,配置完IP地址之后因为ip addr命令不符合我们的习惯,需要添加ifconfig命令 输入命令 yum -y install net-tools 即可解决

  9. 3.2_springBoot2.1.x检索之JestClient操作ElasticSearch

    这里介绍Jest方式交互, 导入jest版本 <!--导入jest--> <dependency> <groupId>io.searchbox</groupI ...

  10. USACO2004 cube stacking /// 带权并查集 oj1302

    题目大意: 以N ( 1 ≤ N ≤ 30,000 )个堆栈开始,每个堆栈包含一个单独的立方体.执行P(1≤ P ≤100,000)的操作. 有两种类型的操作:移动和计数. *在移动操作中,将 包含方 ...