• springboot无法加载静态资源css和js文件


    今天碰到的一个低级错误

    如果springboot无法加载静态资源css和js文件,有以下可能出现的情况,而我是最后一种!!!

    (1)未设置静态扫描路径,这有两种方式

       第一个方式:

        创建一个MyConfig类继承WebMvcConfigurerAdapter

    package com.bo.bookdb;

    /**
    * @author:hgt
    * @version:1.0
    * @date:2020/5/12
    * @description:com.bo.bookdb
    *
    * 因为默认路径虽然是在static下,
    * 但并没有包含static 下的各个文件夹,
    * 因此当我们把静态文件移入这些文件夹后,
    * spring boot就不认识了。
    * 因此,为了让spring boot认识,
    * 我们需要添加一个配置类来把我们自己的路径添加进去,
    * 具体代码如下
    */
    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 MyConfig extends WebMvcConfigurerAdapter{

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
    }

       第二个方式:
          在application.properties当中添加
          
    spring.resources.static-locations=classpath:/resources/,classpath:/static/,classpath:/templates/




    (2)你设置了扫描路径,却依旧在html文件href路径中增加了static等字眼。这是不对的!!!
      正确示例:
    <link href="/css/hello.css" rel="stylesheet"/>



    (3)第三个错:link标签的属性未添加rel="stylesheet"
        正确示例:<link href="/css/hello.css" rel="stylesheet"/>




    额外话题:
    如果感觉自己写的都对,可以先试试清理浏览器缓存,这个真的很烦人


    补充:第二天又测试了一下,发现了static的资源又访问不了,然后我又稍微做了些修改,
    发现只要你的static里面还有子包,你都可以href路径添加../  就OK了
    示例:
    <link href="../css/index.css" rel="stylesheet">

    如此终于得到解决!!!

    如果你的系统的html单纯的输入地址而无法找到,也许你需要在pox.xml中配置如下(放在build标签里面):
    <resources>
    <resource>
    <directory>src/main/java</directory>
    <includes>
    <include>**/*.xml</include>
    </includes>
    </resource>
    <resource>
    <directory>src/main/webapp</directory>
    <!--注意此次必须要放在此目录下才能被访问到 -->
    <targetPath>META-INF/resources</targetPath>
    <includes>
    <include>**/**</include>
    </includes>
    </resource>
    <resource>
    <directory>src/main/resources</directory>
    <filtering>true</filtering>
    <includes>
    <include>**/*</include>
    </includes>
    </resource>
    </resources>






    
    
    
    
    
    
      
  • 相关阅读:
    Django知识总结(一)
    Django知识总结(二)
    Django知识总结(三)
    机器学习领域主要术语的英文表达
    Python的进程与线程--思维导图
    MySQL数据库--思维导图
    5.18 每日小三练
    5.14 每日小三练
    5.12 每日小三练
    5.9 每日小三练
  • 原文地址:https://www.cnblogs.com/dfym80/p/12879662.html
Copyright © 2020-2023  润新知