博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringBoot_04 静态资源映射规则和模板引擎Thymeleaf
阅读量:3967 次
发布时间:2019-05-24

本文共 8247 字,大约阅读时间需要 27 分钟。

静态资源映射规则和模板引擎Thymeleaf


本人是个新手,写下博客用于自我复习、自我总结。

如有错误之处,请各位大佬指出。
学习资料来源于:尚硅谷


使用SpringBoot

1)、创建SpringBoot应用,选中我们需要的模块;

2)、SpringBoot默认将这些场景配置好了,只需要在配置文件中指定少量配置就可以运行起来;
3)、自己编写业务代码;

简例

先像前几篇文章一样,创建一个SpringBoot应用,这次选中web模块。

生成好之后,最基本的web的快速开发,只要像下面这样,建一个controller(实现了一个简单的helloworld),就可以完成,像之前一样。
在这里插入图片描述
HelloController.java

package com.guigu.springboot.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class HelloController {
@ResponseBody @RequestMapping("/hello") public String hello(){
return "Hello World" ; }}

然后在网页上,输入localhost:8080/hello,即可查看到Hello World。

那么对于CSS一类的文件,应该放在什么位置上,其实是有规定的,这就有关于SpringBoot对静态资源的映射规则。

SpringBoot对静态资源的映射规则

先来分析一段 WebMvcAutoConfiguration.class 中的一段代码:

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(WebMvcAutoConfiguration.getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl)); } } } //配置欢迎页 @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)); return welcomePageHandlerMapping; } //配置图标 @configuration @ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true) public static class FaviconConfiguraion {
public final ResourceProperties resourceProperties; public FaviconConfiguraion(ResourceProperties resourceProperties){
this.resourceProperties = resourceProperties; } @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(this.resourceProperties.getFaviconLocations()); return requestHandler; } }

根据代码:

1)、所有 /webjars/** ,都去classpath:/META-INF/resources/webjars/ 下找资源;

webjars:以jar包的方式引入静态资源;

进入webjars官网:
就可以将流行的前端框架,以maven依赖的方式导入进来。还可以选择对应版本。
之后在pom.xml文件中引入即可。

比如,我想调用jquery的3.3.1版本,

就在pom.xml,dependencies标签中加入:(这段引入在官网中可以找到)

org.webjars
jquery
3.3.1

之后就可以找到:

在这里插入图片描述
也就是说,可以在网页中输入 localhost:8080/webjars/jquery/3.3.1/jquery.js ,它就可以找到这个文件。那么在访问的时候,只需要写webjars下面资源的名称即可。

2)、"/**" 访问当前项目的任何资源,(静态资源的文件夹)

“classpath:/META-INF/resources/”

“classpath:/resources/”
“classpath:/static/”
“classpath:/public/”
“/”:当前项目的根路径

也就是说,只要文件无法处理,就会在这些文件夹中寻找。

在这里插入图片描述
在网页中输入localhost:8080/abc,只要无响应,就会去这些文件夹中寻找abc。

3)、欢迎页;静态资源文件夹下的所有index.html文件;

输入localhost:8080/ 就会自动去寻找静态资源文件夹下的index页面

比如:

在这里插入图片描述

    
Title

首页

4)、配置图标;所有的 **/favicon.ico 都是在静态资源文件夹下寻找。

在这里插入图片描述

这样打开页面,就会发现出现图标。(是上面的那个小图标)
在这里插入图片描述

5)、当然也可以手动修改路径,但是没必要。

在application.properties中:

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

模板引擎Thymeleaf

SpringBoot的项目是以jar包的形式,而且是嵌入式的tomcat,所以它默认是不支持JSP的。那么使用静态资源的方式,就会带来很多的麻烦。因此,SpringBoot就提供了模板引擎。就比如JSP、Velocity、Freemarker、Thymeleaf等都是模板引擎。模板引擎,就是我们先写一个静态模板,但是其中有一些值是动态的,这些值又会从一些指定数据中获得,那么将这些数据和模板交给模板引擎,由模板引擎来帮我们组装、解析、填充到指定的位置,最后将这个数据写出去。

SpringBoot推荐的是Thymeleaf,它语法更简单,功能更强大。

引入thymeleaf:

org.springframework.boot
spring-boot-starter-thymeleaf

切换thymeleaf版本时需要注意,每一个thymeleaf都有对应的layout,具体对应版本,去github上直接搜索thymeleaf 和 thymeleaf-layout-dialect 或者去官网,可以查找。但是版本问题会经常出现(我尝试了好久),以下为我自己能用的版本号。

3.0.11.RELEASE
2.1.1

Thymeleaf使用和语法

首先,从ThymeleafProperties.class中看到以下代码:

@ConfigurationProperties(    prefix = "spring.thymeleaf")public class ThymeleafProperties {
private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8"); private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html"); public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html"; ,,,,}

也就是说,只要我们把HTML页面放在classpath:/templates/ 下,thymeleaf就能自动渲染。

package com.guigu.springboot.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controllerpublic class HelloController {
@ResponseBody @RequestMapping("/hello") public String hello(){
return "Hello World" ; } @RequestMapping("/success") public String success(){
return "success"; }}

在这里插入图片描述

success.html:

    
Title

成功!

使用:

1、导入thymeleaf的名称空间

 

2、使用thymeleaf语法(简例)

    
Title

成功!

这是显示欢迎信息

如果不经过模板引擎解析,直接访问,会显示前端写的数据:这是显示欢迎信息。

而通过引擎解析访问,它就会把它变成指定数据信息。
这样前后端的合作就可以实现了。

3、具体的语法规则

像上面的,th:text;改变当前元素里面的文本内容;

th后,可加任意的html属性,来替换原生属性的值,比如:

这是显示欢迎信息

那么,能用的用法就很多了,具体的可以参考usingthymeleaf.pdf文档查阅。

特征 属性
片段包含(类似于jsp:include) th:insert ,th:replace
遍历(类似于c:forEach) th:each
条件判断(类似于c:if) th:if,th:unless,th:switch,th:case
声明变量(类似于c:set) th:object,th:with
任意属性修改(支持prepend,append) th:attr,th:attrprepend,th:attrappend
修改指定属性默认值 th:value,th:href,th:src
修改标签体内容 th:text(转义特殊字符),th:utext(不转义特殊字符)
声明片段 th:fragment

接下来考虑和表达式相关的问题。

几个表达式语法:

${...} :获取变量值。*{...} :在功能上和${...}一样。可以配合th:object="${session.user}"使用。:

Name: Sebastian.

Surname: Pepper.

Nationality: Saturnn.

#{...} :取国际化内容@{...} :定义URL:@{/order/process(execID=${execId},execType='FAST')}~{...} :片段引用表达式:
...

它还支持字面量、文本操作、数字运算、布尔运算、比较运算、条件运算、特殊符号。

例子

package com.guigu.springboot.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import java.util.Arrays;import java.util.Map;@Controllerpublic class HelloController {
//查出一些数据,在页面展示 @RequestMapping("/success") public String success(Map
map){
map.put("hello","

你好

"); map.put("users", Arrays.asList("zhangsan","lisi","wangwu")); return "success"; }}
    
Title

成功!

这是显示欢迎信息



[[${user}]]

效果图:

在这里插入图片描述
其他的用法可以自己试验。

转载地址:http://jayki.baihongyu.com/

你可能感兴趣的文章
Java~在使用isAlive时, 将线程对象已构造参数的形式传递给Thread对象时进行start启动时, 使用this和Thread.currentThread的差异
查看>>
Java~使用synchronized修饰静态方法带来的问题 与 同步synchronized代码块不使用String作为锁对象的原因
查看>>
Java~util包中Timer的使用, 演示cancel方法 和 对比schedule和scheduleAtFixedRate方法
查看>>
Java~并发容器ConcurrentHashMap、ConcurrentLinkedQueue、阻塞队列BlockingQueue的实现原理与使用
查看>>
Java~并发流程控制的手段CountDownLatch、CyclicBarrier、Semaphore和Exchanger工具类的学习和使用
查看>>
Java~学习Executor框架, 了解ThreadPoolExecutor和ScheduledThreadPoolExecutor
查看>>
Java~在maven项目中添加junit依赖实现单元测试(@After、@Before 、@Ignore、@Test)的使用
查看>>
selenium~使用unittest测试框架,批量执行测试脚本,addTest、makeSuite、TestLoader、discover的使用
查看>>
Spring~Bean的作用域(单例模式、原型模式)等, Bean的自动装配方法, @AutoWired和@Resource的区别
查看>>
Spring~使用注解配置开发(@Component、@Repository、@Service、@Controller)和使用JavaConfig实现配置开发
查看>>
Spring~使用Mybatis-Spring包将MyBatis与Spring整合(俩种方式实现), 解决静态资源不导入问题
查看>>
MyBatis~配置解析, 属性(properties)、设置(settings)、类型别名(typeAliases)、环境配置(environments)、映射器(mappers)
查看>>
MyBatis~使用万能的ResultMap解决属性名和字段名不一致问题,实现分页查询 | 使用注解实现简单的CRUD(注意@Param的使用)
查看>>
MyBatis~关联的嵌套Select查询和关联的嵌套结果映射(association元素的使用)、集合的嵌套Select查询和集合的嵌套结果映射(collection的使用)
查看>>
MyBatis~动态 SQL之if,choose、when、otherwise,trim、where、set,foreach,sql的使用,实现带逻辑代码的sql语句
查看>>
SpringMVC~使用RestFul风格和SpringMVC俩种方式接收数据, 对比model、modelMap、modelAndView三种方式数据显示到前端
查看>>
SpringBoot~解决三个疑惑,为什么pom.xml文件中导入依赖不需要版本? 它是如何实现自动配置的? 它是如何启动运行的?
查看>>
SpringBoot~使用javaConfig的形式扩展WebMvcConfigurer配置, 实现自定义拦截器、默认转发、自定义视图解析器
查看>>
Java~HashMap1.7与1.8对比, ConcurrentHashMap 1.7和1.8对比, concurrent包下安全集合类的对比
查看>>
MySQL~InnoDB引擎解决脏读,不可重复读,幻读,丢失更新的原理(lock事务锁、自增长锁、Record Lock、Gap Lock、Next-Key Lock、死锁)
查看>>