Spring Boot:引用js,css,jquery静态资源报错

报错背景

最近一直在使用Bootstrap框架,可以快速在下面网页上搭建前端界面。ibootstrap
但是搭建完,需要引用css,js,以及jquery,这样效果才可以使用。

错误方法一

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<link href="https://cdn.bootcss.com/twitter-bootstrap/3.0.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/twitter-bootstrap/3.0.1/js/bootstrap.min.js"></script>

上面是我使用的方法,可以直接在网站上引用这些代码。

方法一报错

但是第二天,这方法突然没有了,并且前台报错

Refused to execute script from ‘https://cdn.bootcss.com/twitter-bootstrap/3.0.1/js/bootstrap.min.js’ because its MIME type (‘text/html’) is not executable, and strict MIME type checking is enabled.
Spring Boot:引用js,css,jquery静态资源报错
网站上的用不了,那我下载换成本地的吧。

解决方法

倒腾了一早上,终于找到了解决方法,并且在Spring Boot 上的一些坑也解决了,希望你们可以得到帮助。

下面是eclipse里的SSM项目
Spring Boot:引用js,css,jquery静态资源报错

WEB-INF里的Homepage.jsp 需要引用static 里的静态资源
Spring Boot:引用js,css,jquery静态资源报错

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%
	pageContext.setAttribute("APP_PATH",request.getContextPath());
%>
<script src="${APP_PATH }/static/js/jquery-3.3.1.min.js"></script>
<link href="${APP_PATH }/static/bootstrap-3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="${APP_PATH }/static/bootstrap-3.3.7/js/bootstrap.min.js"></script>
<title>主页</title>
</head>
<body>
</body>
</html>

你可以用这个方法引入。

<script src="/travel/static/js/jquery-3.3.1.min.js"></script>
<link href="/travel/static/bootstrap-3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="/travel/static/bootstrap-3.3.7/js/bootstrap.min.js"></script>

当然你也可以这样,加上项目的名字

IDEA中的Spring Boot 引用

下面是IDEA里的Spring Boot项目
Spring Boot:引用js,css,jquery静态资源报错

解决办法

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"/>
    <title>买家商品列表</title>
    <script src="/sell/js/jquery-3.3.1.min.js"></script>
    <script src="/sell/bootstrap-3.3.7/js/bootstrap.min.js"></script>
    <link href="/sell/bootstrap-3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
</body>
</html>

IDEA里面的Spring Boot项目的默认静态资源的路径为:
spring.resources.static-locations=
classpath:/METAINF/resources/,
classpath:/resources/,
classpath:/static/,
classpath:/public/

所以不要加了/static路径。

新人采坑记录,希望可以帮到你