springboot访问templates的html并加载html里的js
时间: 2023-11-27 11:53:51 浏览: 108
要访问Spring Boot中的模板并加载HTML中的JS脚本,可以按照以下步骤进行:
1. 在Spring Boot中配置模板引擎,例如使用Thymeleaf:
```
@Configuration
public class WebConfig {
@Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver());
return engine;
}
private ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setPrefix("classpath:/templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
}
```
2. 在模板HTML文件中引入JS脚本:
```
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>My Page</title>
<script type="text/javascript" src="/js/myScript.js"></script>
</head>
<body>
<h1 th:text="${pageTitle}">Page Title</h1>
<p th:text="${pageContent}">Page Content</p>
</body>
</html>
```
3. 在Spring Boot中配置静态资源路径,例如JS脚本:
```
@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/js/**").addResourceLocations("classpath:/static/js/");
}
}
```
4. 现在,可以访问模板HTML页面并加载JS脚本了,例如:
```
http://localhost:8080/myPage
```
其中,`myPage`是模板HTML文件名,位于`classpath:/templates/`路径下。`myScript.js`是JS脚本文件名,位于`classpath:/static/js/`路径下。
阅读全文