Spring Boot---(4)访问静态资源(图片,HTML,CSS等)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq1021979964/article/details/88636692

SpringBoot访问静态资源

Javaweb程序中,一般都是需要访问静态资源的,比如CSS,JS,JPG等。

在SpringBoot中,访问静态资源需要在几个固定的目录下,都是在resources中。

访问页面需要在templates中,并在控制层添加返回页面文件的名字。

访问图片之类的在static中,但不只是static,还有/META-INF/resources,resources,public等。

优先级顺序

优先级顺序为:/META-INF/resources>resources>static>public

如果静态文件名字相同,会访问到优先级高的文件夹,因为Springboot对静态文件的访问,是一层层的往下访问,一旦找到就不会往下找了,就像是设计模式中的责任链模式一样。

在maven中加入这两个依赖包

<!-- web启动器-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 访问静态资源-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

在resources中创建几个文件夹,我静态资源中四个文件夹都创建是为了比较好的展示优先级,一般创建一个static就行了,自己再到static中扩展即可,application使用默认的就行

静态页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
        静态访问
</body>
</html>

访问静态页面的Controller类

package com.kevin.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author kevin
 * @version 1.0
 * @description     访问静态资源
 * @createDate 2019/3/13
 */
@Controller
public class StaticController {

    // 访问static中的index.html的地址:localost:8080/index
    @RequestMapping("/index")
    public String index(){
        return "index";
    }


}

主程序类

package com.kevin;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author kevin
 * @version 1.0
 * @description     启动类
 * @createDate 2019/3/12
 */
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }

}

访问地址:http://localhost:8080/echarts.min.js

扫描二维码关注公众号,回复: 5629032 查看本文章

访问地址:http://localhost:8080/jquery-ui.min.css

访问地址:http://localhost:8080/tupian.jpg

tupian.jpg这个名称在static中也有,里面的图片是海贼王,但是输入访问地址并没有访问到这个而是resources的,所以证明了优先级static比resouces低

访问静态页面地址:http://localhost:8080/index

 
  

猜你喜欢

转载自blog.csdn.net/qq1021979964/article/details/88636692