zoukankan      html  css  js  c++  java
  • springboot读取静态资源文件的方式

    springboot的请求路径一般会经过Controller处理,但是静态资源文件在请求之后是直接返回的。这涉及到俩个配置项。

    spring.mvc.static-path-pattern=/**
    spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
    上面俩个是他们的默认配置,如果项目中没有任何配置,项目会以这种配置执行。

    spring.mvc.static-path-pattern指的是请求路径。
    spring.resources.static-locations指的是,静态资源目录,目录按配置顺序由先到后,优先级由高到低。
    举例说明:
    如果配置为
    spring.mvc.static-path-pattern:/static/**,
    spring.resources.static-locations:classpath:/static/,classpath:/public/

    即http://localhost:8088/static/index.html的请求会是一个静态请求;而http://localhost:8088/index.html的请求不是一个静态请求。
    那么http://localhost:8088/static/index.html这个请求,就会在现在static目录下,寻找index.html文件(注意:寻找的是index.html文件,而不是static/index.html),如果找到了响应请求,如果找不到,再在public文件夹下寻找。在需要注意的是,在
    另外:spring是先处理Controller请求的,当项目中有处理static/index.html路径的方法时,如图:

     请求是不会去寻找静态资源的。




    这种配置方式是在application.properties文件中配置的,除此之后还可以在项目中配置。

    项目中配置方式:
    package com.tsinkai.ettp.config;
    
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    @Configuration
    public class WebMvcConfig extends WebMvcConfigurerAdapter{
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        }
        
    }

    这两种方式的配置是同事存在的,并不冲突。

    另外写在html中的静态路径需要注意的问题:

    正确写法:<script src="/static/layui/layui.js">

    错误写法:<script src="static/layui/layui.js">

    static前的/,一定要写好,否则会在请求js时出现404.

    原因:

    正确请求的路径:http://localhost:8088/static/layui/layui.js

    错误请求的路径:http://localhost:8088/thymeleaf/static/layui/layui.js

    即,如果不写/,那么最终的请求会加上处理该请求的Controller类的RequestMapping,如图

    就算这个世道烂成一堆粪坑,那也不是你吃屎的理由
  • 相关阅读:
    Codeforces 1163E 高斯消元 + dfs
    Codeforces 1159E 拓扑排序
    Codeforces 631E 斜率优化
    Codeforces 1167F 计算贡献
    Codeforces 1167E 尺取法
    Gym 102007I 二分 网络流
    Codeforces 319C DP 斜率优化
    Codeforces 1163D DP + KMP
    Comet OJ
    Vue 的响应式原理中 Object.defineProperty 有什么缺陷?为什么在 Vue3.0 采用了 Proxy,抛弃了 Object.defineProperty?
  • 原文地址:https://www.cnblogs.com/whalesea/p/11678200.html
Copyright © 2011-2022 走看看