springboot访问静态资源如webapp下的js、css等

springboot访问静态资源如webapp下的js、css等

springboot对静态资源的默认扫描路径是:

classpath:/static
classpath:/public
classpath:/resources
classpath:/META-INF/resources

首先,springboot默认建立是没有webapp文件夹的,需要自己创建:

在这里插入图片描述

主要是配置两个路径,webapp放在和java,resource统一目录下,如下:

在这里插入图片描述

如何访问到webapp下的这些css、img、js中的静态资源呢?

1、pom.xml

<resources>
    <resource>
        <directory>src/main/webapp</directory>
        <targetPath>META-INF/resources</targetPath>
        <includes>
            <include>**/**</include>
        </includes>
    </resource>

这样,springboot才会将对应资源编译到target目录中,如下图:

在这里插入图片描述

2、配置

写一个配置类:

package com.tmall.tmallspringboot.config;


import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@EnableWebMvc
@Configuration
public class CORSConfiguration implements WebMvcConfigurer {

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

17行为将"/**" 映射到target中的"classpath:/META-INF/resources/"。

注意"classpath:/META-INF/resources/"中最后的/不能丢

综上,就可以找到了!

在这里插入图片描述

发布了28 篇原创文章 · 获赞 16 · 访问量 3196

猜你喜欢

转载自blog.csdn.net/Newbie_J/article/details/94777260