更多信息:
本篇算是学习笔记
编辑器:IntelliJ IDEA 2020.1
目录
Web开发
创建SpringBoot应用,选中根据情况选择自己需要的模块;
SpringBoot已经默认帮我们把环境自动配置好了,只需要在配置文件中指定少量配置就可以运行起来。
然后根据自己的需要编写代码。
注意:这个过程的难点就是,你对Spring Boot帮你自动配置的原理是否了解,清楚Spring Boot的自动配置会对你的程序造成什么影响,再根据自己的程序适当的对Spring Boot的自动配置进行修改和扩展。
自动配置包
web模块
xxxxProperties:配置类来封装配置文件的内容;
SpringBoot对静态资源的映射规则
第一种映射规则
我们可以以webjar导入静态资源
https://www.webjars.org/
<!--引入jquery-webjar-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.4.0</version>
</dependency>
将要导入的代码选中,导入到项目的pom.xml文件中,然后再Reimport一下项目,就可以导入相关的jar包了。
其文件正好是符合/webjar/的结构的,所有 /webjars/ ,都去 classpath:/META-INF/resources/webjars/ 找资源;
例如:项目启动后,我们可以访问localhost:8080/webjars/jquery/3.4.0/jquery.js
localhost:8080/webjars/jquery/3.4.0/jquery.slim.js
第二种映射规则
ResourceProperties.class
getStaticPathPattern()
第二种映射规则:如果没人处理,"/**" 访问当前项目的任何资源,都去(静态资源的文件夹)找映射
静态资源文件夹
“classpath:/META-INF/resources/”,
“classpath:/resources/”,
“classpath:/static/”,
“classpath:/public/”,
“/”:当前项目下的根路径
@Bean
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider));
welcomePageHandlerMapping.setCorsConfigurations(this.getCorsConfigurations());
return welcomePageHandlerMapping;
}
getWelcomePage()
private Optional<Resource> getWelcomePage() {
String[] locations = WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations());
return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
}
getResourceLocations()
欢迎页; 静态资源文件夹下的所有index.html页面;被"/**"映射
localhost:8080/ 也符合"/**",静态资源文件夹下找index页面
#自己定义静态文件目录,以前的默认配置静态文件目录路径就不行了
spring.resources.static-locations=classpath:/hello/,classpath:/atguigu/
模板引擎
例子:JSP、Velocty、Thymeleaf
Thymeleaf
Thymeleaf is a modern server-side Java template engine for both web
and standalone environments.Thymeleaf’s main goal is to bring elegant natural templates to your
development workflow — HTML that can be correctly displayed in
browsers and also work as static prototypes, allowing for stronger
collaboration in development teams.With modules for Spring Framework, a host of integrations with your
favourite tools, and the ability to plug in your own functionality,
Thymeleaf is ideal for modern-day HTML5 JVM web development — although
there is much more it can do.
作用
只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;
导入Thymeleaf的启动器
Github: https://github.com/thymeleaf/thymeleaf/releases
版本切换
<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>
启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Thymeleaf的使用和语法
自动配置下的Thymeleaf
ThymeleafAutoConfiguration
ThymeleafProperties
Thymeleaf使用文档
链接:https://pan.baidu.com/s/1HplunU3OVn323_xp6f8dcA
提取码:1854
例子
HelloController 提供hello的数据
package com.atguigu.springboot04webrestfulcrud.controller;
import com.atguigu.springboot04webrestfulcrud.exception.UserNotExistException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Arrays;
import java.util.Map;
@Controller
public class HelloController {
/*
@RequestMapping({"/","/index.html"})
public String index(){
return "index";
}
*/
@ResponseBody
@RequestMapping("/hello")
public String hello(@RequestParam("user") String user) {
if (user.equals("aaa")) {
throw new UserNotExistException();
}
return "Hello World";
}
/**
* 查出用户数据,在页面展示
*/
@RequestMapping("/success")
public String success(Map<String, Object> map) {
map.put("hello", "<h1>hello</h1>");
map.put("users", Arrays.asList("zhangsan", "lisi", "wangwu"));
/*classpath:templates/success.html
在ThymeleafProperties的属性里面定义了
*/
return "success";
}
}
语法规则
th:任意html属性;
作用:用数据来源去替换原生属性的值;
表达式语法
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: _
例子