SpringBoot2.1.X 访问静态资源(img、html、css、js)
一、目录结构
src/main/java:存放代码
src/main/resources
static: 存放静态文件,比如 css、js、image, (访问方式 http://localhost:8080/js/main.js)
templates:存放静态页面jsp,html,tpl
config:存放配置文件,application.properties
二、如果要访问templates目录下的页面,那么就必须添加Springboot访问静态资源的Jar文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
注意:如果不引人这个依赖包,html文件应该放在默认加载文件夹里面,
比如resources、static、public这个几个文件夹,才可以访问;
启动主程序,运行效果
再写个Controller访问(注意这是默认的返回视图的文件位置)
//注意不能用@RestController,这个返回的是JSON格式的,现在要返回的是HMTL。
@Controller
public class FilterController {
@RequestMapping("/my/index")
public Object index(){
return "index";
}
}
HMTL页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="../css/index.css">
<script src="../js/index.js"></script>
</head>
<body>
<h1>how are you!</h1>
<a href="javascript:fun()"><img src="../images/1.png" /></a>
<hr/>
<img src="../images/2.jpg"/>
</body>
</html>
启动:
三、如果在resouces目录下,创建自己的目录myjs时,那又如何访问这个目录下的文件呢?
默认配置 官网地址:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html\#boot-features-spring-mvc-static-content
application.properties文件中必须要写配置:
spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/myjs/
记得在后面加上 ,classpath:/myjs/
启动访问: http://localhost:8080/test.js
还没有评论,来说两句吧...