32、WebJars与thymeleaf渲染引擎

1、webjar使用

<!-- 使用webjar管理前端资源,此处引入bootstrap和jquery方便演示 -->

    <dependency>

         <groupId>org.webjars</groupId>

         <artifactId>jquery</artifactId>

         <version>2.1.1</version>

    </dependency>

    <dependency>

         <groupId>org.webjars</groupId>

         <artifactId>bootstrap</artifactId>

         <version>3.3.7</version>

    </dependency>

    <!-- 辅助定位静态资源,省略 webjar的版本:http://localhost:8080/webjars/jquery/3.1.0/jquery.js路径中可以省略3.1.0 -->

    <dependency>

         <groupId>org.webjars</groupId>

         <artifactId>webjars-locator</artifactId>

         <version>0.32</version>

    </dependency>

    <!-- thymeleaf渲染模板 -->

    <dependency>

         <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-thymeleaf</artifactId>

    </dependency>

 

 

2、webjar内部打包结构

 

以jquery为例:

META-INF

    └─maven

        └─org.webjars.bower32、WebJars与thymeleaf渲染引擎

            └─jquery

                └─pom.properties

                └─pom.xml

    └─resources

        └─webjars

            └─jquery

                └─3.2.1

    WebJars的静态资源存放位置与普通的Javaweb静态资源的存放位置是不同的,

普通的Javaweb项目的静态资源文件往往是存放在webapp文件目录下,而当我

们要将静态资源打进jar包时,我们就得采用WebJars的静态资源存放原则,那

就是将静态资源文件存放到

src.main.resources.META-INF.resources.webjars

目录下

 

    WebJar的内容的路径必须是如下格式:META-INF/resources/webjars/${name}/${version}

该格式是由WebJars官网明文规定的,是必须要遵守的规范格式。之所以选择这个路径结构,是因为它可以得到

Java Web框架的广泛支持,并且包含路径中的版本号,因此可以很容易地使用具有侵略性的缓存。

注意:

(1) 由于我们是将静态资源文件打入到jar包中,所以说我们要将packaging定义为jar格式而非传统的war格式

(2) 由于WebJars的命名规范中,jar包的路径名中必须含有版本号${version},如:META-INF/resources/webjars/${name}/${version}

    之所以webjars能使用webjars/**访问是因为其设置了静态资源路径映射(mvc):

    SpringBoot将对/webjars/**的访问重定向到classpath:/META-INF/resources/webjars/**

 

    我们在添加静态资源文件时,肯定不想将资源文件加入到含有${version}的路径中,因为随着项目的发展,

    项目的jar版本会出现版本号的不同。比如说从1.0-SNAPSHOT变更到2.0-SNAPSHOT,亦或是从

    1.0-RELEASE变更到2.0-RELEASE。假如说我们将静态文件资源存放到含有版本号的路径中,

    那么Maven的版本变动直接带来的结果就是项目的静态资源文件位置频繁的迁移,但是项目的jar中又明确的要求含有${version},

    我们的解决办法是在pom.xml文件中加入如下代码:

      <properties>

        <projectName>image-cut</projectName>

        <projectVersion>1.0-RELEASE</projectVersion>

        <springframework.version>4.3.10.RELEASE</springframework.version>

      </properties>

      <build>

        <resources>

          <resource>

            <directory>${project.basedir}/src/main/resources/META-INF/resources/webjars/${projectName}</directory>

            <targetPath>META-INF/resources/webjars/${projectName}/${projectVersion}</targetPath>

          </resource>

        </resources>

      </build>

    通过上面的properties来统一管理项目的项目名以及版本号。然后在下面的build中,我们将静态资源文件打入到含有${version}的jar包之中。我的工程编译如下:

 

  <!-- 用于打包资源文件,默认情况下maven只打包src/main/resource下的资源 -->

    <resources>

      <resource>

          <!-- 指定build资源到哪个目录,默认是base directory -->

        <targetPath>META-INF/resources/webjars/${project.name}/${project.version}</targetPath>

        <!-- 将webjars目录下的自己的脚本[js或css]打包成jar并按照webjars格式放到targetPath目录,前端使用方式同jquery或boostrap -->

        <directory>${project.basedir}/src/main/resources/static</directory>

        <!-- 指定包含文件的patterns,符合样式并且在directory目录下的文件将会包含进project的资源文件 -->

        <includes>

          <include>**/*.js</include>

        </includes>

      </resource>

    </resources>

 

打包前格式:

 

打包后文件格式:

 

打包后运行jar包,然后访问:http://localhost:8080/webjars/spring_demon/js/test.js

 

特别注意:

    通过build.resources方式打包资源会覆盖原有的资源打包,所以如果配置必须配置所有的静态资源打包方式,包括templates,static等,否则导致资源不会打包,无法访问;

默认的staitc和templates是被打包到BOOT-INF\classes\staitc 或BOOT-INF\classes\templates目录,也就是默认打包的classes类目录中;

为了不影响其他资源,我们可以保持默认资源不动,自己的资源按照自己的方式打包:

<build>

     <plugins>

          <plugin>

              <groupId>org.springframework.boot</groupId>

               <artifactId>spring-boot-maven-plugin</artifactId>

          </plugin>

     </plugins>

     <!-- 用于打包资源文件,默认情况下maven只打包src/main/resource下的资源 -->

    <resources>

      <resource>

          <!-- 指定build资源到哪个目录,默认是base directory -->

        <targetPath>${project.build.outputDirectory}/BOOT-INF/classes</targetPath>

        <!-- 将webjars目录下的自己的脚本[js或css]打包成jar并按照webjars格式放到targetPath目录,前端使用方式同jquery或boostrap -->

        <directory>${project.basedir}/src/main/resources</directory>

      </resource>

      <resource>

          <!-- 指定build资源到哪个目录,默认是base directory -->

        <targetPath>META-INF/resources/webjars/${project.name}/${project.version}</targetPath>

        <!-- 将webjars目录下的自己的脚本[js或css]打包成jar并按照webjars格式放到targetPath目录,前端使用方式同jquery或boostrap -->

        <directory>${project.basedir}/src/main/resources/static</directory>

        <!-- 指定包含文件的patterns,符合样式并且在directory目录下的文件将会包含进project的资源文件 -->

        <includes>

          <include>**/*.js</include>

        </includes>

      </resource>

    </resources>

  </build>

 

页面中访问静态资源方式:

(1) 在spring容器中访问

    <mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>

(2) 在servlet3容器中访问

    <mvc:resources mapping="/webjars/**" location="/webjars/"/>

    或者在Java中加入如下配置信息:

    @Configuration

    @EnableWebMvc

    public class WebConfig extends WebMvcConfigurerAdapter {

      @Override

      public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");

      }

    }

(3) 在浏览器中访问

jquery访问:/webjars/jquery/3.2.1/dist/jquery.js

全路径访问资: http://localhost:8080/项目名/webjars/jquery/3.2.1/dist/jquery.js

例如:

<head>

    <meta charset="UTF-8">

    <title>Dalaoyang</title>

    <link rel="stylesheet" href="/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css" />

    <script src="/webjars/jquery/3.1.1/jquery.min.js"></script>

    <script src="/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js"></script>

</head>

Tomcat启动类加载顺序:

(1)Bootstrap引导类

  加载JVM启动所需的类,以及标准扩展类(位于jre/lib/ext下)

(2)System系统类

  加载tomcat启动的类,比如bootstrap.jar,通常在catalina.bat或者catalina.sh中指定。位于CATALINA_HOME/bin下。

(3)Common通用类

  加载tomcat使用以及应用通用的一些类,位于CATALINA_HOME/lib下,比如servlet-api.jar

(4)webapp应用类

  在这里,Tomcat会优先加载/WEB-INF/classes然后再加载/WEB-INF/lib/*.jar。

  也就是说,我们的静态资源文件其实是在最后Tomcat在加载jar包时才被加载进去的。

 

3、静态资源

 

a.默认的静态资源目录

SpringBoot默认配置下,提供了以下几个静态资源目录:

(1)/META-INF/resources:classpath:/META-INF/resources/

(2)/resources:classpath:/resources/

(3)/static:classpath:/static/

(4)/public:classpath:/public/

优先级从从高到低.我们将静态资源放到以上路径或放到者我们把静态文件直接放到webapp下,springboot中的springmvc模块会默认这些地方进行扫描,如果找到,就会直接响应。访问这些资源不需要添加/static,/public或/resources,如src/main/resource/static/js/test.js文件,访问路径直接填写为:

http://localhost:8080/js/test.js即可,如果直接访问http://localhost:8080/则会默认从以上四个路径中查找index.html文件如果存在则作为首页进行展示;如果要添加自己的路径映射,则可以使用@EnableWebMvc注解编写自己的mvc配置类。

 

当然,一般情况下,默认的静态资源访问路径就能满足我们的需求,当然我们可以自定义静态资源路径的配置可以通过

spring.resources.static-locations配置指定静态文件的位置:

(1) 通过配置文件配置

#配置静态资源

spring:

  resources:

    #指定静态资源目录列表

    static-locations: classpath:/mystatic/,classpath:/test/

(2) 通过修改代码配置

@Configuration

public class MyWebAppConfigurer

        extends WebMvcConfigurerAdapter {

    @Override

    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/testStatic/**").addResourceLocations("classpath:/testStatic/");

        super.addResourceHandlers(registry);

    }

}

 

这样使用代码的方式自定义目录映射,并不影响Spring Boot的默认映射,可以同时使用

 

b.favicon.ico图标

如果在配置的静态资源目录中有favicon.ico文件,SpringBoot会自动将其设置为应用图标。

 

c.欢迎页面

SpringBoot支持静态和模板欢迎页,它首先在静态资源目录查看index.html文件做为首页,若未找到则查找index模板

注意:

(1)默认情况下, 网页存放于static目录下, 默认的"/"指向的是~/resouces/static/index.html文件

(2)如果引入了thymeleaf, 则默认指向的地址为~/resouces/templates/index.html

(3)在引入thymeleaf后, 如果仍需要访问~/static/index.html, 则可以使用重定向:return "redirect:/index.html"

(4)HTML中引入webjars时, 需导入类似下面的包

    <dependency>

         <groupId>org.webjars</groupId>

         <artifactId>bootstrap</artifactId>

         <version>3.3.7</version>

    </dependency>

         <dependency>

         <groupId>org.webjars</groupId>

         <artifactId>jquery</artifactId>

         <version>3.1.1</version>

    </dependency> 

    

4、thymeleaf渲染引擎

(1)介绍

a.Thymeleaf的优点是它是基于HTML的,即使视图没有渲染成功,也是一个标准的HTML页面。

b.前期技术都是JSP,JSP的优点是它是Java EE容器的一部分,几乎所有Java EE服务器都支持JSP。

     缺点就是它在视图表现方面的功能很少,假如我们想迭代一个数组之类的,只能使用<% %>来包括Java语句进行。

     虽然有标准标签库(JSTL)的补足,但是使用仍然不太方便。另外JSP只能在JavaEE容器中使用,

     如果我们希望渲染电子邮件之类的,JSP就无能为力了。

(2)使用

顶部添加:<html xmlns:th="http://www.thymeleaf.org">, 如下所示:

如果控制层存放model数据,那么在渲染引擎中可以通过EL表达式获取:

@GetMapping("index")

public String index(ModelMap map) {

    //使用了lombok依赖

    student.setName("test");

    student.setAge(20);

    student.setMale("male");

    student.setStudentNO("2018");

    //将student模型加入视图中

    map.addAttribute("student",student);

    //返回的是页面名(注意这里的页面名与templates下的页面名必须相同)

    return "index";

}

<!DOCTYPE html>

<html lang="en" xmlns:th="http://www.thymeleaf.org">

    <head>

        <meta charset="UTF-8">

        <title>Signin Template for Bootstrap</title>

        <!-- Bootstrap core CSS -->

        <link href="../static/asserts/css/bootstrap.min.css" th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}" rel="stylesheet">

        <!-- Custom styles for this template -->

        <link th:href="/asserts/css/signin.css" rel="stylesheet">

    </head>

    <body>

         <h2>来自Thymeleaf模板的内容</h2>

         <h2>Hello Thymeleaf~</h2>

         <div class="container">

             <div class="alert alert-success">

                 <p th:text="${student.name}"></p>

             </div>

         </div>

    </body>

</html>

 

注意:

(1) 这里th标签会覆盖相应的属性值,只需要将需要Thymeleaf渲染的文件放到/templates下即可交由Thymeleaf引擎渲染

(2) 渲染页面可以通过EL表达式获取信息

原理:

@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";

}

 

配置文件配置:

 

spring:

  thymeleaf:

    prefix: classpath:/templates/

    check-template-location: true

    cache: false

    suffix: .html

    encoding: UTF-8

    content-type: text/html

    mode: HTML5

 

prefix:指定模板所在的目录

check-tempate-location: 检查模板路径是否存在

cache: 是否缓存,开发模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能。

encoding&content-type:这个大家应该比较熟悉了,与Servlet中设置输出对应属性效果一致。 

mode:这个还是参考官网的说明吧,并且这个是2.X与3.0不同,本文自动引入的包是2.15。

 

 

5、静态资源访问配置

   静态资源,例如HTML文件、JS文件,设计到的Spring Boot配置有两项:

(1)“spring.mvc.static-path-pattern”

(2)“spring.resources.static-locations”

    很多人都难以分辨它们之间的差异,所以经常出现的结果就是404错误,无法找到静态资源。 

 

(1)“spring.mvc.static-path-pattern”

    spring.mvc.static-path-pattern代表的含义是我们应该以什么样的路径来访问静态资源,换句话说,只有静态资源满足什么样的匹配条件,Spring Boot才会处理静态资源请求,以官方配置为例:

 

# 这表示只有静态资源的访问路径为/resources/**时,才会处理请求 spring.mvc.static-path-pattern=/resources/**

 

假定采用默认的配置端口,那么只有请求地址类似于“http://localhost:8080/resources/jquery.js”时,Spring Boot才会处理此请求,处理方式是将根据模式匹配后的文件名查找本地文件,那么应该在什么地方查找本地文件呢?这就是“spring.resources.static-locations”的作用了

 

(2)spring.resources.static-locations

“spring.resources.static-locations”用于告诉Spring Boot应该在何处查找静态资源文件,这是一个列表性的配置,查找文件时会依赖于配置的先后顺序依次进行,默认的官方配置如下:

spring.resources.static-locations=classpath:/static,classpath:/public,classpath:/resources,classpath:/META-INF/resources

 

继续以上面的请求地址为例,“http://localhost:8080/resources/jquery.js”就会在上述的四个路径中依次查找是否存在“jquery.js”文件,如果找到了,则返回此文件,否则返回404错误

 

(3)静态资源的Bean配置

    从上面可以看出,“spring.mvc.static-path-pattern”与“spring.resources.static-locations”组合起来演绎了nginx的映射配置,如果熟悉Spring MVC,那么理解起来更加简单,它们的作用可以用Bean配置表示,如下:

 

@Configuration

@EnableWebMvc

public class WebConfig extends WebMvcConfigurerAdapter {

    @Override

    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/resources/**")

                .addResourceLocations("/public-resources/")

                .setCacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic());

    }

}

 

总结:

“spring.mvc.static-path-pattern”用于阐述HTTP请求地址,而“spring.resources.static-locations”则用于描述静态资源的存放位置。

 

快来成为我的朋友或合作伙伴,一起交流,一起进步!
QQ群:961179337
微信:lixiang6153
邮箱:lixx2048@163.com
公众号:IT技术快餐
更多资料等你来拿!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贝壳里的沙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值