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

今天碰到的一个低级错误css

若是springboot没法加载静态资源css和js文件,有如下可能出现的状况,而我是最后一种!!!html

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

   第一个方式:web

    建立一个MyConfig类继承WebMvcConfigurerAdapterspring

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>
相关文章
相关标签/搜索