Spring Boot - part2

1. 静态资源处理

1.1 静态资源映射规则①

SpringBoot中,SpringMVC的web配置都在 WebMvcAutoConfiguration 这个配置类里面。

WebMvcAutoConfigurationAdapter 中有很多配置方法;其中一个方法: addResourceHandlers 添加资源处理

概括:所有的 /webjars/** , 都需要去 classpath:/META-INF/resources/webjars/ 找对应的资源,具体内容如下所示。

@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();
    // webjars 配置
    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));
    }
}
webjars

Webjars本质就是以jar包的方式引入我们的静态资源 , 我们以前要导入一个静态资源文件,直接导入即可。

SpringBoot需要使用Webjars,我们可以去搜索一下:https://www.webjars.org

要使用jQuery,我们要引入jQuery对应版本的pom依赖!

<dependency>
	<groupId>org.webjars</groupId>
	<artifactId>jquery</artifactId>
	<version>3.6.0</version>
</dependency>

导入完毕,查看webjars目录结构,并访问Jquery.js文件!
jquery.js访问:只要是静态资源,SpringBoot就会去对应的路径寻找资源,我们这里访问 :http://localhost:8080/webjars/jquery/3.6.0/jquery.js
在这里插入图片描述

1.2 静态资源映射规则②

找staticPathPattern发现第二种映射规则 : /** , 访问当前的项目任意资源,它会去找resourceProperties 这个类。

可以在resources(相当于classpath)根目录下新建对应的文件夹,都可以存放我们的静态文件;

// 进入方法
public String[] getStaticLocations() {
    return this.staticLocations;
}
// 找到对应的值
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
// 找到路径
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { 
    "classpath:/META-INF/resources/",
    "classpath:/resources/", 
    "classpath:/static/", 
    "classpath:/public/" 
};

1.3 自定义静态资源路径

通过配置文件来指定一下:哪些文件夹是需要我们放静态资源文件的,在application.properties中配置:

spring.resources.static-locations=classpath:/coding/,classpath:/kuang/

1.4 首页处理

欢迎页,静态资源文件夹下的所有 index.html 页面;被 /** 映射。
比如我访问 http://localhost:8080/ ,就会找静态资源文件夹下的 index.html

2. Thymeleaf

Thymeleaf 是 SpringBoot 推荐的模板引擎,像jsp也是一种模板引擎。
模板引擎的作用:在写一个页面模板,有些值是动态的,需要写一些表达式。而这些值,就是我们在后台封装一些数据。然后把这个模板和这个数据交给我们模板引擎,模板引擎按照数据帮你把这表达式解析、填充到指定的位置,然后把这个数据最终生成一个想要的内容给写出去。
模板引擎

2.1 引入Thymeleaf

引入pom依赖

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

Maven会自动下载jar包
themeleaf

2.2 分析

找Thymeleaf的自动配置类: ThymeleafProperties (ctrl+shift+r)

@ConfigurationProperties(
    prefix = "spring.thymeleaf"
)
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING;
    public static final String DEFAULT_PREFIX = "classpath:/templates/";
    public static final String DEFAULT_SUFFIX = ".html";
    private boolean checkTemplate = true;
    private boolean checkTemplateLocation = true;
    private String prefix = "classpath:/templates/";
    private String suffix = ".html";
    private String mode = "HTML";
    private Charset encoding;
}

可以看到默认的前缀和后缀,只需要把html页面放在类路径下的templates文件夹下,thymeleaf就可以自动帮忙渲染。

测试

  1. 编写TestController
@Controller
public class TestController {

   @RequestMapping("/t1")
    public String test1(){
       //classpath:/templates/test.html
        return "test";
    }
}
  1. 编写一个测试页面 test.html 放在 templates 目录下
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>测试页面</h1>
</body>
</html>
  1. 启动项目测试

测试

2.3 使用语法

1、可以使用任意的 th:attr 来替换Html中原生属性的值
th:attr
2、表达式

Simple expressions:(表达式语法)
Variable Expressions: ${...}:获取变量值;OGNL;
    1)、获取对象的属性、调用方法
    2)、使用内置的基本对象:#18
         #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.

    3)、内置的一些工具对象:
      #execInfo : information about the template being processed.
      #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.
==================================================================================

  Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;
  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: _

练习测试:

  1. 编写一个Controller,并放一些数据
@Controller
public class TestController {
    @RequestMapping("/t2")
    public String test2(Map<String,Object> map){
    	//存放数据
       map.put("msg","<h1>hello</h1>");
       map.put("users", Arrays.asList("邹小胖","连小伟"));
       return "test";
    }
}
  1. 测试页面读取数据
<body>
    <h1>测试页面</h1>

    <div th:text="${msg}"></div>
    <!-- 不转义 -->
    <div th:utext="${msg}"></div>

    <!-- 遍历数据 -->
    <!--th:each每次遍历都会生成当前这个标签:官网#9-->
    <h4 th:each="user: ${users}" th:text="${user}"></h4>

    <h4>
        <!-- 行内写法 -->
        <span th:each="user : ${users}">[[${user}]]</span>
    </h4>
</body>

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值