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访问: