学习SpringBoot(精华文章二)

本文是接上一篇:学习SpringBoot(精华文章一)

四、Web开发

使用springboot

四.1、创建springboot应用

1.创建springboot应用,选中我们需要的模块;
2.springboot默认已经将这些场景配置好了,只需在配置文件中指定少量的配置就可以运行起来。
3.自己编写业务代码
自动配置原理?详见二.8
1.xxxAutoConfiguration:帮我们给容器中自动配置组件
2.xxxProperties:配置类来封装配置文件的内容

四.2、Springboot对静态文件的映射规则

添加资源映射:

		@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) {
			return new WelcomePageHandlerMapping(
					new TemplateAvailabilityProviders(applicationContext),
					applicationContext, getWelcomePage(),
					this.mvcProperties.getStaticPathPattern());
		}

		//设置自己喜欢的图标
		@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;
			}
4.2.1.所有/webjars/**下的路径访问,都去classpath:/META-INF/resources/webjars/找资源;

/webjars/**:以jar包的方式引入静态资源。webjars官网

4.2.2.引入的webjars:

引入的webjars
访问路径:localhost:8080/webjars/jquery/3.3.1/jquery.js
在访问的时候,只需要写webjars下面的资源名称即可。

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.3.1</version>
</dependency>
4.2.3.“/**”访问当前项目的任何资源:(静态资源文件夹)
"classpath:/META-INF/resources/",
"classpath:/resources/",
"classpath:/static/", 
"classpath:/public/
"/":当前项目的根目录

webjars资源路径
访问路径下的任何东西,如:localhost:8080/abc,如果没人处理,默认都去访问类路径下的静态资源:
localhost:8080/abc === 去静态资源找abcclasspath:/resources/

4.2.4 欢迎页:静态资源文件下的所有index.html页面;被“/**”映射;

localhost:8080/,默认就找静态资源文件的下面。

4.2.5 所有的**/favicon.ico都是在静态资源文件下面找图片来作为图标

不管是访问任意路径层下面的favicon.ico,图标都是在静态资源文件下

4.2.6 改变静态文件夹的路径

在application.properties中,指定hello和bootcrud的文件夹。

spring.resources.static-locations=classpath:/hello/,classpath:/bootcrud/

spring.resources.static-locations是数组,所以再指定多路径的时候需要加逗号。

四.3 模板引擎

Jsp、Velocity、Freemarker、Thymeleaf
模板引擎很多,但是思想都是一样的:
模板引擎的作用
SpringBoot推荐的模板引擎:Thymeleaf。被称为高级语言的模板引擎。
语法更简单,功能更强大。

4.3.1 引入Thymeleaf

怎么引:对于springboot来说,都是starter就OK了。

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

因为springboot默认的thymeleaf版本是2.1.6,所以:

修改依赖版本的方法:

<properties>
    <java.version>1.8</java.version>
    <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
    <!--layout是布局功能扩展-->
    <!--布局功能的支持,2.0以上版本支持thymeleaf3-->
    <!--比如:thymeleaf3,layout2以上版本;thymeleaf2,layout1-->
    <thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
</properties>
4.3.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>

controller:

@RequestMapping("/success")
public String success(Map<String,Object> map){
    map.put("hello","你好");
    return "success";
}

四.4、语法规则

4.4.1、th:text:改变当前元素里面的文本内容。

th: 任意的HTML属性,来替换原生的值

thymeleaf官方网站:找到Using Thymeleaf,下载文档

在这里插入图片描述

4.4.2、thymeleaf能写哪些表达式?
Simple expressions:
    Variable Expressions: ${...} 	-----> 获取变量值:OGNL表达式。也是用得最多最强大的表达式
    		1.可以获取对象的属性值,可以调用方法
    		2.能使用的内置对象有:
            #ctx : the context object.(当前上下文对象)
            #vars: the context variables.(当前上下文对象里面的值)
            #locale : the context locale.(区域信息)
    			web环境下:
            #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.
    			例:
    			${person.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: *{...}  -----> 变量的选择表达式,和${...}的功能是一样的。
    		注:有一个补充的功能:主要是配合${...},如:(参见thymeleaf文档4.3)
    			例:
    			<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>
				*就等于${session.user},可以直接取出session.user下面的firstName、lastName
    Message Expressions: #{...}	-----> 获取国际化内容
    Link URL Expressions: @{...} 	-----> 定义URL
    Fragment Expressions: ~{...} 	-----> 片段引用表达式
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: _
	例:
	比如三元运算符:
	if判断如果成立用then,不成立用else,如果不想做什么操作,直接_
4.4.3语法规则练习例子:

controller:

@RequestMapping("/success")
public String success(Map<String,Object> map){
    map.put("hello","<h1>你好</h1>");
    map.put("name", Arrays.asList("陈二狗","王境泽","二营长"));
    return "success";
}

在classpath:/templates/下的success.html:

<!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>
<hr/>
    <div th:utext="${hello}"></div>
<hr/>
    <!-- th:each每次遍历都会生成当前这个标签,也就是h4。-->
    <!-- h4里面的内容拿th:text里面的值 -->
    <!-- 这个效果是3个h4 -->
    <h4 th:text="${names}" th:each="names:${name}"></h4>
<hr/>
    <!-- 一个h1,里面带了三个span -->
    <h1>
        <!-- [(${name})]为行内写法 -->
        <span th:each="names:${name}">[(${names})]</span>
    </h1>
</body>
</html>

最后的运行效果:
在这里插入图片描述
总结:
第一个hr线:
th:text为转义特殊字符,所以它会直接把整个字符串给输出出来。
th:utext为不转义字符,所以会按照它(h1标签)自己原本的意思显示出来。h1在html中是表示什么,就给值上样式。
第二个hr线:
把th:each写在h4上,所以页面会显示三个h4,遍历了这个数组。h4标签的内容就是th:text的值。
第三个hr线:
把数组遍历在span标签上,所以再h1标签下会有三个span标签,span里面的值就是(${name})输出的值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值