SpringBoot_5 SpringBoot对静态资源的映射规则

SpringBoot对静态资源的映射规则

     由于springboot是以jar包的方式打包程序的因此是没有webapp目录的。

     那么我们的css/js/html文件要保存在什么地方???要解决这个问题,我们要了解一个Java类“WebMvcAuotConfiguration”,因为与web开发相关的自动配置都是由这个类完成的。

     spring-boot-autoconfigure-2.4.0.jar---》META-INF--》spring.factories

     org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration

@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();
   if (!registry.hasMappingForPattern("/webjars/**")) {
      customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/")
            .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)
            .setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
   }
   String staticPathPattern = this.mvcProperties.getStaticPathPattern();
   if (!registry.hasMappingForPattern(staticPathPattern)) {
      customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
            .addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
            .setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl)
            .setUseLastModified(this.resourceProperties.getCache().isUseLastModified()));
   }
}

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = 
{ "classpath:/META-INF/resources/",
 "classpath:/resources/", 
"classpath:/static/",
 "classpath:/public/" };

1.静态资源的保存位置所有/webjars/** 

     webjars:将需要使用的静态资源打成jar包,我们如果需要就将整个jar导入值本项目就可以使用了。

     静态资源打成jar包查看位置:

     https://www.webjars.org/

     以JQuery为例来使用一下webjars方式:

     1.在pom.xml文件中导入JQuery的jar依赖

<!--导入jquery的jar包-->
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.5.1</version>
</dependency>

        导人以后的结果

 

     2.测试访问我们导入的jquery文件

        启动服务,在浏览器的地址栏中直接访问jquery文件

        http://localhost:8080/webjars/jquery/3.5.1/jquery.js

2.默认静态资源文件的位置

     WebProperties.java

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = 
{ "classpath:/META-INF/resources/",
 "classpath:/resources/", 
"classpath:/static/",
 "classpath:/public/" };
  1. "classpath:/META‐INF/resources/",  

          [src/main/resources/META-INF/resources/]--运行之前需要打包一下

      2."classpath:/resources/"=== [src/main/resources/resources]

     3.”classpath:/static/”==== [src/main/resources/static]

     4."classpath:/public/"== [src/main/resources/public]

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

         经过测试验证,其访问顺序为 "classpath:/META-INF/resources/" > "classpath:/resources/" > "classpath:/static/" > "classpath:/public/" 

4.自定义静态资源位置

     可以在application.properties中配置修改静态资源文件夹路径。

     spring.web.resources.static-locations=classpath:/test/

       http://localhost:8080/test.html

5.模板引擎

     由于springboot是以jar包的方式打包程序的,而不是web项目,再者在springboot中我们用的是嵌入式的tomcat服务器,因此springboot项目是不支持动态页面的运行,所以如果我们都将页面处

理成静态页面的话,那么到时候见加载数据的时候就需要大量的js来向后台请求数据回填到静态页面上,这样的话就会比较麻烦。所用springboot才为我们提供了模板引擎。

     常见的模板引擎有JSP、Velocity、Freemarker、Thymeleaf

     SpringBoot为我们推荐Thymeleaf模板引擎;因为他语法更简单,功能更强大。

     Thymeleaf模板引擎的使用:

       1.引入Thymeleaf模板引擎的依赖包【启动器】

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

     2.使用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";
}

        只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;

     3.类、创建控制器

public class GoodsBean {
    private int id;
    private String name;
    private int price;
    private String picture;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getPicture() {
        return picture;
    }

    public void setPicture(String picture) {
        this.picture = picture;
    }
}
package com.wangxing.springbootdemo8.controller;

import com.wangxing.springbootdemo8.bean.GoodsBean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
public class MyController {

    @RequestMapping("good.do")
    public String goodsController(Model model){
        List<GoodsBean> goodslist = new ArrayList<GoodsBean>();
        GoodsBean goodsBean1 = new GoodsBean();
        goodsBean1.setId(001);
        goodsBean1.setName("灯泡");
        goodsBean1.setPrice(1999);
        goodsBean1.setPicture("img/close.PNG");

        GoodsBean goodsBean2 = new GoodsBean();
        goodsBean2.setId(002);
        goodsBean2.setName("小米9");
        goodsBean2.setPrice(1999);
        goodsBean2.setPicture("img/xiaomi8.jpg");

        goodslist.add(goodsBean1);
        goodslist.add(goodsBean2);

        model.addAttribute("goodsbeanlist",goodslist);

        return "goodsmain";
    }

}

     注意:传递给页面是数据值是通过请求处理方法中的参数设置的,

            请求处理方法中的参数的类型:  List<GoodsBean> goodslist = new ArrayList<GoodsBean>();

            请求处理方法的返回值是模板页面的名称。

     4.创建模板页面,模板页面默认是”.html”

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>商品详情页</title>
</head>
<body>
    <table border="1px">
        <tr align="center">
            <td>编号</td>
            <td>名称</td>
            <td>价格</td>
            <td>图片</td>
        </tr>
        <tr align="center" th:if="${goodsbeanlist.size()==0}">
            <td><h3>没有记录</h3></td>
        </tr>
        <tr align="center" th:if="${goodsbeanlist.size()!=0}" th:each="good:${goodsbeanlist}">
            <td th:text="${good.id}"></td>
            <td th:text="${good.name}"></td>
            <td th:text="${good.price}"></td>
            <td><img th:src="${good.picture}" th:height="80px" th:width="50px"></td>
        </tr>
    </table>
</body>
</html>

          xmlns:th="http://www.thymeleaf.org"--给html页面引入thymeleaf命名空间,引入thymeleaf命名空间我们就可以在html页面中使用thymeleaf语法,显示动态数据。

          thymeleaf语法:

     th:任意html属性;来替换原生html的属性的值

         <span id="span1"></span>

        <span th:id="${id}"></span>

     例如:

        <h1 th:text="${address}"></h1>

        th:text---控制h1元素的text属性值,text属性值就是html元素的文本内容

    thymeleaf表达式:

#{...}:国际化消息 
${…}:变量取值 
*{…}:当前对象/变量取值 
@{…}:url表达式 
~{…}:片段引用 
判断/遍历: 
th:if ---th:if=”${id}==1001”
th:unless 
th:each --th:each=”user:${users}”  --- th:text=”${user}”
th:switch、th:case

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值