欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot学习笔记6web开发(1)

程序员文章站 2022-03-14 09:06:42
...

SpringBoot学习笔记—Day05

使用spring boot:
1.) 创建springboot应用选择我们需要的模块
2.) springboot已经将我们选中的场景配置好了,只需要少量的配置就可以使用
3.) 自己编写业务代码

自动配置原理?
这个场景sprigboot帮我们配置了什么?
能不能修改?
能修改哪些配置?
能不能扩展?

xxxxAutoConfiguration //给容器中自动添加组件的类
xxxxProperties //配置类中来封装配置文件的内容的类

springboot对静态资源的映射规则
在springboot 里面,SpringMVC的配置都在WebMVCAutoConfiguration里面
WebMVCAutoConfiguration源码

		@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));
			}
		}
		
		@Bean //欢迎页映射
		public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
				FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
			WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
					new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
					this.mvcProperties.getStaticPathPattern());
			welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
			welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
			return welcomePageHandlerMapping;
		}

addResourceHandlers此方法用来添加资源文件映射
所有/webjars/**,都去classpath:/META-INF/resources/webjars/找资源
webjars,以jar包的方式引入静态资源
超链接webjars官网中可以查找到webjars的maven依赖 —webjars
SpringBoot学习笔记6web开发(1)

<!--引入jquery的webjars-->
        <dependency>
            <groupId>org.webjars.bower</groupId>
            <artifactId>jquery</artifactId>
            <version>3.2.1</version>
        </dependency>

在访问的时候,只需要访问webjars下的资源路径即可
在addResourceHandlers方法中,看到resourceProperties
ResourceProperties源码

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {

我们可以在配置文件中设置和静态资源有关的参数,缓存时间等
在addResourceHandlers方法中,还可以看到registry.addResourceHandler(staticPathPattern),这个staticPathPattern="/**",也就是访问当前项目下的任何路径
接着看到getResourceLocations(this.resourceProperties.getStaticLocations())这行.接着查到这个getStaticLocations()方法获取到的是 { “classpath:/META-INF/resources/”,“classpath:/resources/”, “classpath:/static/”, “classpath:/public/” }数组,也就是说,这个4个路径是可以存放静态资源的,

@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/asserts/img/bootstrap-solid.svg
``SpringBoot学习笔记6web开发(1)
welcomePageHandlerMapping方法
在WebMVCAutoConfiguration中还加入了组件welcomePageHandlerMapping的方法,作用是配置欢迎页,在welcomePageHandlerMapping方法中调用了getWelcomePage()方法,
getWelcomePage()方法源码

		private Optional<Resource> getWelcomePage() {
			String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());
			return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
		}

		private Resource getIndexHtml(String location) {
			return this.resourceLoader.getResource(location + "index.html");
		}

可以看到getStaticLocations(),获取的还是那4个静态资源路径,后面加上index.html,接着看到mvcProperties.getStaticPathPattern()这里,获取到的是"/ * *",也就是说所有静态文件夹下的index.html都被这个"/ * *"映射
模板引擎
JSP、Velocity、Freemarker、Thymeleaf都属于模板引擎
SpringBoot学习笔记6web开发(1)
我们将后台传来的数据,与前端静态页面共同传给模板引擎,利用后台传来的数据,解析静态页面,最终组合成一个新的页面

SpringBoot推荐的Thymeleaf; 语法更简单,功能更强大;
对于新版本的(我创建springboot时时用的idea推荐的2.3.1的版本),要想使用Thymeleaf模板引擎,只需要导入thymeleaf的starter即可,因为他内部设置的thymeleaf.version跟thymeleaf-layout-dialect.version都是很高的版本,如果是低版本的springboot可能还要在properties标签中重新设置这俩个标签的版本

<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.4.1</thymeleaf-layout-dialect.version>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Thymeleaf语法
我们找到Thymeleaf的配置文件映射类ThymeleafProperties

@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"; //默认后缀

	/**
	 * Whether to check that the template exists before rendering it.
	 */
	private boolean checkTemplate = true;

只要将html页面放到类路径下templates包内,thymeleaf就可以访问的到
在html内写thymeleaf时,可以先导入一个thymeleaf的名称空间,这样在写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>
<div th:text="${hello}"></div>
</body>
</html>

语法规则
可以任意替换html标签的属性

<div id="div1" class="divClass" th:id="${hello}" th:class="${hello}" th:text="${hello}"></div>

浏览器源代码显示为:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>你好!</h1>
<div id="你好" class="你好">你好</div>
</body>
</html>

与jsp比较
SpringBoot学习笔记6web开发(1)
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: _

使用示例

@Controller
public class TestController {

    @RequestMapping("/success")
    public String success(Map<String,Object> maps){
        maps.put("hello","<h1>你好</h1>");
        maps.put("users", Arrays.asList("张三","李四","王五"));
        //默认去classpath:/templates/success.html页面
        return "success";
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="div1" class="divClass" th:id="${hello}"
     th:class="${hello}" th:text="${hello}"></div>
    <div th:utext="${hello}"></div>
    <div th:text="${users[0]}"></div>
    <div th:text="${users[1]}"></div>
    <div th:text="${users[2]}"></div>
    <!--th每次遍历都会生成当前标签,一共生成3个h4标签-->
<h4 th:each="user:${users}" th:text="${user}"></h4>
<h4>
    <span th:each="user:${users}">[[${user}]]</span>
</h4>
</body>
</html>

SpringBoot学习笔记6web开发(1)