springBoot----Thymeleaf使用和基本语法

使用springboot

  1. 创建springboot应用,选择自己需要的模块
  2. spring boot已经进行了默认配置,自己只需要在配置文件中写少量的配置就可以了
  3. 编写业务逻辑的代码
    要明白自动配置,springboot 为场景设置添加了那些组件
    xxxxAutoConfiguration xxxxProperties

1.静态资源的映射规则

registry.addResourceHandler添加资源映射
@ConfigurationProperties(
    prefix = "spring.resources",
    ignoreUnknownFields = false
)
public class ResourceProperties {
设置和静资源有关的参数,缓存时间等

添加资源映射的规则:

public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
            } else {
                Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
                CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
               //
                if (!registry.hasMappingForPattern("/webjars/**")) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }
				//
                String staticPathPattern = this.mvcProperties.getStaticPathPattern();
                if (!registry.hasMappingForPattern(staticPathPattern)) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

            }
        }

1.访问所有的/webjars/**,都要去classpath:/META-INF/resources/webjars/ 目录下找资源
访问的时候只需要:webjar/资源名称
webjars : 所有的静态资源都要以jar 包的形式导入springboot 项目

对比:
之前写页面,只有在webapp 的目录下放好Jquery …文件就可以了,但是在springboot 中必须以jar包的形式导入
Jquery(webjars)导入Springboot的目录结构:
在这里插入图片描述
访问Jquery 的地址:localhost:8080/META-INF/resources/webjars/jquery/3.3.1-2/juery.js
webjars 官网:https://www.webjars.org/

<!--引入JQuery 的 webjar  -->
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>jquery</artifactId>
			<version>3.3.1-2</version>
		</dependency>

2. /** : 访问当前项目的任何资源,如果没有任何处理就去一下的位置找对应的资源

"classpath:/META-INF/resources/" 
"classpath:/resources/",
"classpath:/static/"
 "classpath:/public/"
 "/ " : 当前项目的根目录
  1. 欢迎页的映射设置
 @Bean
        public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext) {
            return new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
        }

静态资源文件夹下所有的index.html 页面,被/** 映射
例如:访问local host:8080/ 就会去找所有静态资源文件夹下的index.html

4. 所有的 * */favico.ico 都在静态资源文件下找


2.模板引擎

springboot 默认是不支持jsp 页面,但是如果页面都是静态的将会十分的不方便。所以引入:模板引擎
写一个模板(内含获取数据的表达式),在封装一些数据;将模板和封装的数据====》交给模板引擎:将模板中的表达式解析获取数据,最后变成一个我们想要的内容写回浏览器

springboot推荐使用的模板引擎:thymeleaf(语法简单,功能强大)

thymeleaf

1.导入thymeleaf 应用场景

注意如果要自己修改thymeleaf 的版本,依赖的版本和布局的版本要一致(具体可以百度)
<thymeleaf.version>3.0.11.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
在pom.xml 重新配置,就直接覆盖原本的

通过查看:spring-boot-AutoConfigre jar 包。thymeleaf -----Thymeleafproperties 类中:

 public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";

只要把HTML的页面放在classpath:/templates/   thymenleaf 可以自动渲染
  1. 单纯的返回一个页面
代码在@Controller  方法中
@RequestMapping("/success")
    public String success(){
      //返回的页面的路径是:classpath:/thymeleaf/
    return "success";
    }
    
★★ 没有导入thymeleaf 的依赖,return 是无法到success.html 页面的;
 seccuess 相当于是数据,success.html 页面,thymeleaf 将数据和页面整合,最后得到我们想要的页面

2.查出一些数据,在页面上取值展示

在@Contorller的方法中

@RequestMapping("/success")
    public String success(Map<String,Object> map){
        map.put("hello","你好!!");  //这个数据会被放到请求域中
       return "success";
    }
    要在页面上获取hello 的值

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.pdf 官方文档

  1. 导入thymeleaf 的名称空间
    < html lang="en" xmlns:th="http://www.thymeleaf.org" > 就会有代码提示
  2. 使用thymeleaf 语法
<!--th:text="message" 将div 里面的文本内容设置为:message-->
<div th:text="${hello}"></div>

3.语法规则

1.使用th: 任意属性替换原生属性:

<div id="123" class="class" th:id=""  th:class="" th:text="${hello}"></div>
th:id  替换原生的id   th:class 替换原生的class  th:text  替换原生的内容

在这里插入图片描述
2. th:属性=表达式-----可以写那些表达式
(1)表达式语法:都是OGNL表达式
Variable Expressions: ${…}
-获取对象的属性,调用方法
-使用页面的内置对象:

${里面可以使用的表达式}
#ctx : 当前上下文对象
#locale : 区域信息-------------- ${#{local.country}} 当前的国家区域代号
#vars : 上下文里面的变量值
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.

–使用内置的工具对象

#execInfo
#messages
#uris
#conversions
#dates
#calendars
#numbers
#strings
#objects
#bools
#arrays
#lists
#maps
#aggregates
#ids

(2) 变量的选择表达式
${…}也可以写成*{…};但是有一个补充功能:配合th:Object

 <div th:object="${session.user}">    
   在session 中获取了一个对象user  
   
 <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
 可以直接用*{} 表示这个对象,直接获取属性
 
 <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>   

相当于:

<div> <p>Name:  <span th:text="${session.user.firstName}">   Sebastian</span>.</p> 
 <p>Surname:    <span th:text="${session.user.lastName}">    Pepper</span>.</p>  

(3) #{…} 定义国际化信息

(4)@{…} 定义url

<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3 --> 实现这个跳转并且带上参数
<a href="details.html"   
 th:href="@{http://localhost:8080/gtvg/order/details (orderId=${o.id})}"   >view</a>
@{url  (参数)}
参数使用:key=value
value   : 也可以是获取的值
参数可以是多个: (key=value,key = value ....)
当前项目下url:th:url = "@{/order/details(orderId=${o.id},execId="TAST")}"

(5)~{…} 片段引用表达式

<div th:insert="~{commons :: main}">...</div>

(6)字面量:字符串,数字,布尔值,null
(7) 文本操作:字符串拼接(+),字符串替换(|the name is ${name}|)
(8)数学运算,布尔运算(and or !not ),比较运算(> < >= <= == != 写为: gt lt ge le eq ne)
(9)条件运算:(if)? (then) ,三元运算符: (if)?(then):(else)
(10) 特殊操作: _(不进行任何操作)


操作:

  map.put("hello","<h1>你好!!</h1>");  //这个数据会被放到请求域中
  map.put("users", Arrays.asList("zhangsan","lisi","wangwu"));
  页面获取:
  
<div th:text="${hello}"></div>   对数据转义=====变成纯字符串
<div th:utext="${hello}"></div>   特殊字符不被转义=====实现特殊字符的功能
<div th:text="${users[0]}"></div>

<!--遍历 th:each= 每一次遍历都会生成当前标签 页面上有三个div-->
<div th:text="${user}" th:each="user:${users}"></div>
<hr/>
<!--th:text 的行内写法-->
[[....]] 相当于:th:text    [(.....)]  相当于:th:utext
<h1>
    <span th:each="user:${users}" >[[${user}]]</span>
</h1>

猜你喜欢

转载自blog.csdn.net/Stitch__/article/details/88379043