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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值