springboot中无法访问static下静态资源的问题,如static/js/jquery.js无法访问的问题

本文介绍了在Spring Boot应用中遇到无法访问static目录下静态资源,如jQuery.js的问题及其解决方案。包括理解static资源的访问规则,检查application.properties中的`spring.mvc.static-path-pattern`和`spring.resources.static-locations`配置,以及注意MyWebMVCConfig.java中可能影响静态资源重定向的设置。同时,提供了Thymeleaf中正确引入外部JS文件的方法:`th:src="@{/js/jquery.js}"`,并给出直接访问JS资源的URL示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

thymeleaf中引入外部JS的方式:
(1)在static下新建文件夹放入外部JS文件
在这里插入图片描述
(2)static下的静态资源访问规则可能受application.properties中spring.mvc.static-path-pattern和spring.resources.static-locations有关!
在这里插入图片描述
(3)注意(2)中的配置文件不生效时,和MyWebMVCConfig.java中对静态资源的重定位有关系!

package com.steno.propertiestest.common;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyWebMVCConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("==========静态资源拦截!============");
        //将所有/static/** 访问都映射到classpath:/static/ 目录下
        registry.addResourceHandler("/static/**/").addResourceLocations("classpath:/static/");
    }
}

在这里插入图片描述
(4)thymeleaf中使用th:src="@{/js/jquery.js}"引入外部JS文件

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>springboot-thymeleaf</title>
    <!--
    引入外部JS,注意引入方式为@{}否则不生效,
    另外
    (1)static下的静态资源访问规则可能受application.properties中spring.mvc.static-path-pattern和spring.resources.static-locations有关!
    (2)配置文件不生效时,和MyWebMVCConfig.java中对静态资源的重定位有关系!
    -->
    <script type="text/javascript" th:src="@{/js/jQuery-2.1.4.min.js}"></script>
    <script>
        function testRestGetPage(){
            jQuery.ajax({
                url : "/project/books?page=0&size=2&sort=bookid,desc",
                data : "",
                type : "get",
                datatype : "json",
                success : function(result){
                    console.log(result);
                }
            });
        }
    </script>
</head>

<body>
    <!-- 返回值获取 -->
    <p th:text="'hello, ' + ${book.author} + '的' + ${book.name} + '!'" />
    <button type="button" onclick="testRestGetPage()">查询分页按钮</button>
</body>
</html>

(5)访问JS或者直接访问页面查看加载信息
在这里插入图片描述
直接访问JS:
http://localhost:8081/project/js/jQuery-2.1.4.min.js
在这里插入图片描述
http://localhost:8081/project/static/js/jQuery-2.1.4.min.js访问:
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值