SpringBoot html中引用本地js文件失败的问题

1、问题描述

想在项目中使用jquery,于是从jquery官网下载了最新版本(手动从浏览器中复制到本地的js文件中),并在html文件中添加了引用。目录及引用情况如图。
在这里插入图片描述

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Insert title here</title>
    <script src="../static/jquery.min.js"></script>
    <script type="text/javascript">
		function btnLoginClick() {
            if (typeof jQuery !== 'undefined') {
                alert("Loaded success.");
            } else {
                alert ("Not yet.");
            }
        }
	</script>
</head>
<body>
<button onclick="btnLoginClick()">Click me</button>
</body>
</html>

运行起来一直提示jQuery没有加载。
将script引用换成远程引用就没有问题。

<script src="http://code.jquery.com/jquery-latest.js"></script>

2、解决方案

网上搜了很多资料,有说是从浏览器copy的文本有问题的,但我直接下载别人的js文件也不行。有说是文件编码格式的问题的,但是我确认了html文件和js文件编码格式都是utf-8,加载还是失败。
后来搜资料时发现别人引用js文件的路径跟自己的不太一样(我是直接将js文件拖到html文件中,IDE自己生成的引用路径),遂怀疑是路径的问题。将自己写的脚本移到单独的js文件中,再在html中添加引用。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Insert title here</title>
    <script src="../static/jquery.min.js"></script>
    <script src="../static/myScript.js"></script>
</head>
<body>
<button onclick="btnLoginClick()">Click me</button>
</body>
</html>

发现一样加载失败,故确定是路径的问题。
搜索正确的路径引用的姿势,参考这篇文章,将路径改为

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Insert title here</title>
    <script src="./jquery.min.js"></script>
    <script src="./myScript.js"></script>
</head>
<body>
<button onclick="btnLoginClick()">Click me</button>
</body>
</html>

加载OK。

PS:
另外一个项目中按照上面设置还是加载失败,发现是使用了shiro的缘故。需要在shiro的FilterChain中添加拦截规则,让静态资源可以匿名访问。

@Bean
ShiroFilterChainDefinition shiroFilterChainDefinition() {
    DefaultShiroFilterChainDefinition definition = new DefaultShiroFilterChainDefinition();
    definition.addPathDefinition("/js/**", "anon");
    definition.addPathDefinition("/login", "anon");
    definition.addPathDefinition("/**", "authc");
    return definition;
}
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值