springboot学习3之web开发,springboot对静态资源的映射,thymeleaf标签详解

一、使用spring boot

1、创建springboot应用,选中我们需要的模块
2、springboot已经默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来
3、自己编写业务代码
要了解自动配置原理
这个场景SpringBoot帮我们配置了什么?能不能修改?能修改哪些配置?能不能扩展?等等
所有的自动配置类都是如下格式:

xxxAutoConfiguration:自动配置类
xxxProperties:封装的配置文件

1、springboot对静态资源的映射

WebMvcAutoConfiguration

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));
			}
		}

1、所有/webjars/**,都去classpath:/META-INF/resources/webjars/找资源
webjars:以jar包方式引入静态资源;
资源网站:https://www.webjars.org/
在这里插入图片描述
访问:localhost:8080/webjars/jquery/3.4.1/jquery.js
2、/**访问当前项目的任何资源(静态资源文件夹)

@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/" };

访问:localhost:8080/js/jquery.js

3、欢迎页,静态资源文件夹下的所有index.html页面;被/**映射

@Bean
		public WelcomePageHandlerMapping welcomePageHandlerMapping(
				ApplicationContext applicationContext) {
			return new WelcomePageHandlerMapping(
					new TemplateAvailabilityProviders(applicationContext),
					applicationContext, getWelcomePage(),
					this.mvcProperties.getStaticPathPattern());
		}

4、配置图标
所有的**/favicon.ico都是在静态资源文件下找:

//下面只是部分代码
@Configuration 
		@ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
		public static class FaviconConfiguration implements ResourceLoaderAware {
			@Bean
			public SimpleUrlHandlerMapping faviconHandlerMapping() {
				SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
				mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
				mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",
						faviconRequestHandler()));
				return mapping;
			}
		}

5、配置自定义静态资源文件夹,在application.yml中配置,
注意:如果自己定义了静态的资源文件夹,则系统配置的就失效了。

## 由于是数组,用逗号隔开
spring.resource.static.location=classpath:/hello/,classpath:/wang/

2、模板引擎

1、thymeleaf
th:text: 不解析变量中的html标签,而是直接显示变量值
th:utext:解析变量中html标签,显示不输出标签
在这里插入图片描述
以下文档来自:https://www.cnblogs.com/qianjinyan/p/10418351.html
一、th属性
常用th属性解读
html有的属性,Thymeleaf基本都有,而常用的属性大概有七八个。其中th属性执行的优先级从1~8,数字越低优先级越高。

一、th:text :设置当前元素的文本内容,相同功能的还有th:utext,两者的区别在于前者不会转义html标签,后者会。优先级不高:order=7

二、th:value:设置当前元素的value值,类似修改指定属性的还有th:src,th:href。优先级不高:order=6

三、th:each:遍历循环元素,和th:text或th:value一起使用。注意该属性修饰的标签位置,详细往后看。优先级很高:order=2

四、th:if:条件判断,类似的还有th:unless,th:switch,th:case。优先级较高:order=3

五、th:insert:代码块引入,类似的还有th:replace,th:include,三者的区别较大,若使用不恰当会破坏html结构,常用于公共代码块提取的场景。优先级最高:order=1

六、th:fragment:定义代码块,方便被th:insert引用。优先级最低:order=8

七、th:object:声明变量,一般和*{}一起配合使用,达到偷懒的效果。优先级一般:order=4

八、th:attr:修改任意属性,实际开发中用的较少,因为有丰富的其他th属性帮忙,类似的还有th:attrappend,th:attrprepend。优先级一般:order=5

常用th属性使用
使用Thymeleaf属性需要注意点以下五点:

一、若要使用Thymeleaf语法,首先要声明名称空间: xmlns:th=“http://www.thymeleaf.org

二、设置文本内容 th:text,设置input的值 th:value,循环输出 th:each,条件判断 th:if,插入代码块 th:insert,定义代码块 th:fragment,声明变量 th:object

三、th:each 的用法需要格外注意,打个比方:如果你要循环一个div中的p标签,则th:each属性必须放在p标签上。若你将th:each属性放在div上,则循环的是将整个div。

四、变量表达式中提供了很多的内置方法,该内置方法是用#开头,请不要与#{}消息表达式弄混。

五、th:insert,th:replace,th:include 三种插入代码块的效果相似,但区别很大。

<!DOCTYPE html>
<!--名称空间-->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf 语法</title>
</head>
<body>
    <h2>ITDragon Thymeleaf 语法</h2>
    <!--th:text 设置当前元素的文本内容,常用,优先级不高-->
    <p th:text="${thText}" />
    <p th:utext="${thUText}" />

    <!--th:value 设置当前元素的value值,常用,优先级仅比th:text高-->
    <input type="text" th:value="${thValue}" />

    <!--th:each 遍历列表,常用,优先级很高,仅此于代码块的插入-->
    <!--th:each 修饰在div上,则div层重复出现,若只想p标签遍历,则修饰在p标签上-->
    <div th:each="message : ${thEach}"> <!-- 遍历整个div-p,不推荐-->
        <p th:text="${message}" />
    </div>
    <div> <!--只遍历p,推荐使用-->
        <p th:text="${message}" th:each="message : ${thEach}" />
    </div>

    <!--th:if 条件判断,类似的有th:switch,th:case,优先级仅次于th:each, 其中#strings是变量表达式的内置方法-->
    <p th:text="${thIf}" th:if="${not #strings.isEmpty(thIf)}"></p>

    <!--th:insert 把代码块插入当前div中,优先级最高,类似的有th:replace,th:include,~{} :代码块表达式 -->
    <div th:insert="~{grammar/common::thCommon}"></div>

    <!--th:object 声明变量,和*{} 一起使用-->
    <div th:object="${thObject}">
        <p>ID: <span th:text="*{id}" /></p><!--th:text="${thObject.id}"-->
        <p>TH: <span th:text="*{thName}" /></p><!--${thObject.thName}-->
        <p>DE: <span th:text="*{desc}" /></p><!--${thObject.desc}-->
    </div>

</body>
</html>
后台给负责给变量赋值,和跳转页面。

import com.itdragon.entities.ThObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
public class ThymeleafController {

    @RequestMapping("thymeleaf")
    public String thymeleaf(ModelMap map) {
        map.put("thText", "th:text 设置文本内容 <b>加粗</b>");
        map.put("thUText", "th:utext 设置文本内容 <b>加粗</b>");
        map.put("thValue", "thValue 设置当前元素的value值");
        map.put("thEach", Arrays.asList("th:each", "遍历列表"));
        map.put("thIf", "msg is not null");
        map.put("thObject", new ThObject(1L, "th:object", "用来偷懒的th属性"));
        return "grammar/thymeleaf";
    }
}

二、标准表达式语法
${…} 变量表达式,Variable Expressions

@{…} 链接表达式,Link URL Expressions

#{…} 消息表达式,Message Expressions

~{…} 代码块表达式,Fragment Expressions

*{…} 选择变量表达式,Selection Variable Expressions

变量表达式使用频率最高,其功能也是非常的丰富。所以我们先从简单的代码块表达式开始,然后是消息表达式,再是链接表达式,最后是变量表达式,随带介绍选择变量表达式。

~{…} 代码块表达式
支持两种语法结构
推荐:~{templatename::fragmentname}

支持:~{templatename::#id}

templatename:模版名,Thymeleaf会根据模版名解析完整路径:/resources/templates/templatename.html,要注意文件的路径。

fragmentname:片段名,Thymeleaf通过th:fragment声明定义代码块,即:th:fragment=“fragmentname”

id:HTML的id选择器,使用时要在前面加上#号,不支持class选择器。

代码块表达式的使用
代码块表达式需要配合th属性(th:insert,th:replace,th:include)一起使用。

th:insert:将代码块片段整个插入到使用了th:insert的HTML标签中,

th:replace:将代码块片段整个替换使用了th:replace的HTML标签中,

th:include:将代码块片段包含的内容插入到使用了th:include的HTML标签中,

用一个官方例子来区分三者的不同,第三部分会通过实战再次用到该知识。

<!--th:fragment定义代码块标识-->
<footer th:fragment="copy">
&copy; 2011 The Good Thymes Virtual Grocery
</footer>

<!--三种不同的引入方式-->
<div th:insert="footer :: copy"></div>
<div th:replace="footer :: copy"></div>
<div th:include="footer :: copy"></div>

<!--th:insert是在div中插入代码块,即多了一层div-->
<div>
    <footer>
    &copy; 2011 The Good Thymes Virtual Grocery
    </footer>
</div>
<!--th:replace是将代码块代替当前div,其html结构和之前一致-->
<footer>
&copy; 2011 The Good Thymes Virtual Grocery
</footer>
<!--th:include是将代码块footer的内容插入到div中,即少了一层footer-->
<div>
&copy; 2011 The Good Thymes Virtual Grocery
</div>

thymeleaf语法说明来自:https://www.cnblogs.com/itdragon/archive/2018/04/13/8724291.html

发布了31 篇原创文章 · 获赞 1 · 访问量 5681

猜你喜欢

转载自blog.csdn.net/wjs040/article/details/92974735
今日推荐