Spring Boot web开发(一) 静态资源和模板引擎

目录

1. 静态资源映射规则

1.1 以jar包下形式引入静态资源

1.2 其他静态资源

2. 模板引擎Thymeleaf

2.1 Thymeleaf的引入和使用

2.2 thymeleaf语法规则

2.3 thymeleaf表达式


1. 静态资源映射规则

在讲Spring Boot的静态资源映射规则之前,我们先看一下maven工程对于静态文件是如何处理的。

从上图中我们可以看到所有的静态资源都放在webapp下面,也没有进行其他特殊配置要求。

1.1 以jar包下形式引入静态资源

Spring Boot中有关MVC的配置都在WebMvcAutoConfiguration这个类中,打开这个类看一下。里面有个方法,addResourceHandlers添加资源映射。

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));
                }

            }
        }

所有/webjars/**下面的所有路径访问都在classpath:/META-INF/resources/webjars/找资源。比如我们导入一个jQuery.js,只需要在pom文件中添加相关依赖就可以直接引入了。webjars可以在这儿找:https://www.webjars.org/

添加jQuery依赖:

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

引入完成后会有这样一个文件夹,这样jQuery就算引入成功了。访问的时候需要写webjars下资源的名称http://localhost:8080/webjars/jquery/3.4.1/jqurey.js

1.2 其他静态资源

"/**" 访问当前项目的任何资源,都去(静态资源的文件夹)找映射,我们只需要将静态资源文件放在以下几个文件下就可以了,这是默认的静态资源文件夹。如果我们自己定义静态资源文件夹,在配置文件中添加:(注:自定义静态资源文件夹后,默认的静态资源文件夹会失效)

spring.resources.static-locations=classpath:/chtw,classpath:/chtw1
#自定义静态资源文件夹,如需定义多个,用逗号分开
"classpath:/META-INF/resources/", 
"classpath:/resources/",
"classpath:/static/", 
"classpath:/public/" 
"/":当前项目的根路径

2. 模板引擎Thymeleaf

模板引擎指用于Web开发为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的HTML文档。

在java领域,表现层技术主要有三种:jsp、freemarker、velocity。

jsp是Java web阶段最常用的一种模板引擎(前面用的SSM框架就采用了jsp作为模板引擎)
优点:
1、功能强大,可以写java代码
2、支持jsp标签(jsp tag)
3、支持表达式语言(el)
4、官方标准,用户群广,丰富的第三方jsp标签库
5、性能良好。jsp编译成class文件执行,有很好的性能表现
缺点:
jsp没有明显缺点,非要挑点骨头那就是,由于可以编写java代码,如使用不当容易破坏mvc结构。

而JSP技术spring boot 官方是不推荐的,在tomcat上,jsp不能在嵌套的tomcat容器解析,也不能在打包成可执行的jar的情况下解析。spring boot支持的模板引擎有thymeleaf。Thymeleaf是一个Java库。它是一个XML / XHTML / HTML5模板引擎,能够应用于转换模板文件,以显示您的应用程序产生的数据和文本。它尤其适合于基于XHTML / HTML5的web服务应用程序,同时它可以处理任何XML文件,作为web或独立的应用程序。

2.1 Thymeleaf的引入和使用

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

这个地方,可以看到存放我们需要使用模板引擎的html页面的存放地址和文件的拼接后缀。那么thymeleta是如何使用的呢?举一个例子。创建一个controller。

package com.chtw.controller;


import com.fasterxml.jackson.annotation.JsonSetter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author CHTW
 * @date 2019-09-01-22:08
 */
@Controller
public class HelloController {


   @RequestMapping({"/hello","/hello.html"})
    public String index(){
        return "hello";
        //Thymeleaf会帮我们拼上前缀和后缀
    }

}

在templates文件下加创建一个hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
</head>
<body>
<h1>hello</h1>
</body>
</html>

启动服务器,如果没有模板引擎的时候,我们是访问不到hello.html这个页面的,因为templates不是静态资源文件夹。当我们引入Thymeleaf后,当我们访问controller的时候,controller回返回一个String类型的值,这个值就是html页面的名称,比如我要访问hello.html,那这个时候返回的String就是hello。

启动服务器,访问:http://localhost:8080/hello

2.2 thymeleaf语法规则

在html中引入thymeleaf的名称空间

在html标签中添加一行代码

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>hello</title>
</head>
<body>
<h1>hello</h1>
<div th:text="${hello}"></div>
</body>
</html>

其中th:text表示改变当前元素里面的文本内容;

语法规则:th:任意html属性;来替换原生属性的值

为了方便讲解,我们将刚刚的controller进行简单的修改

package com.chtw.controller;


import com.fasterxml.jackson.annotation.JsonSetter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author CHTW
 * @date 2019-09-01-22:08
 */
@Controller
public class HelloController {


   @RequestMapping({"/hello","/hello.html"})
    public String index(Model model){
        model.addAttribute("hello","hello.html访问成功!");
        return "hello";
    }
    /**
   
}

启动服务器访问:http://localhost:8080/hello,可以看到我们在后端存的值,在前端通过th:text取到了。

2.3 thymeleaf表达式

变量表达式:变量表达式即OGNL表达式或Spring EL表达式(在Spring术语中也叫model attributes)。如下所示: 
  ${........}:获取变量值,使用方法如上一个例子th:text="${hello}";

选择(星号)表达式  :用一个预先选择的对象来代替上下文变量容器(map)来执行,如下:*{........}

文字国际化表达式:允许我们从一个外部文件获取区域文字信息(.properties),用Key索引Value

表达式还有很多,我这里就举例最常用的几种。具体可以参考这位大神的介绍:thymeleaf参考手册

本人联系方式2329095893,欢迎各位进行学习讨论

欢迎关注熊熊出没ING公众号,不定时跟新Java、python、信息安全等相关知识哦。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值