SpringBoot无法访问静态资源(js、css、image)的问题

场景

新建SpringBoot项目,继承父项目,导入依赖。


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>com.qianyugroupId>
    <artifactId>demoartifactId>
    <version>1.0-SNAPSHOTversion>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.2.3.RELEASEversion>
        <relativePath/> 
    parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
    dependencies>
project>

/resources/templates/文件夹下,新建index.html文件


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>indextitle>
head>
<body>
<h1>index界面h1>
<script type="application/javascript" src="/js/sayhello.js">script>
<script>
    hello();
script>
body>
html>

index.html文件里面引入的js文件是/resources/static/js/文件夹下的sayhello.js

function hello() {
    alert('hello')
}

新建Controler

@Controller
public class IndexController {
    @GetMapping("/")
    public String index(){
        return "index";
    }
}

新建启动类,启动SpringBoot程序:

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

可见js文件顺利引入:
运行结果

加入拦截器

新建拦截器,作用:打印访问网站的用户的ip地址

@Component
public class LogInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
        System.out.println("ip :" + req.getRemoteAddr() + " 访问了网站");
        return true;
    }
}

配置拦截器:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private LogInterceptor logInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(logInterceptor)
                .addPathPatterns("/**");
    }
}

再次访问网站:
错误界面

解决方法

经查阅资料,参考文章:Spring注解@EnableWebMvc使用坑点解析,发现Spring Boot 默认提供Spring MVC 自动配置,不需要使用@EnableWebMvc注解,于是将@EnableWebMvc注释掉就可以访问静态资源了。
SpringBoot无法访问静态资源(js、css、image)的问题_第1张图片

你可能感兴趣的:(java高级)