使用SpringBoot访问图片

前言

SpringBoot发布关于web端的项目的时候,我们逃不开的就是静态资源的访问,当我们显示图片的时候,路径的书写就显得十分重要。我们知道SpringBoot 的Web端项目推荐我们使用html页面,这时候我们想使用jsp相关的语法的时候,我们就需要导入thymeleaf模板。作为这个大前提,我们进行今天图片显示的讲解。

1. 简单访问项目图片的方法

[1] 在pom.xml中导入thyemleaf模板

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

[2] SpringBoot中对静态资源访问的规定:
SpringBoot只扫描resources下的静态资源文件.
resources/
resources/resources/
resources/static/
resources/templates/ (这里我们一般放我们的html页面,因为SpringBoot会通过thymeleaf进行路径的直接映射)

下图是效果:
使用SpringBoot访问图片_第1张图片
使用SpringBoot访问图片_第2张图片
[3] 启动主程序,访问 http://localhost:8080/img/0.jpg
使用SpringBoot访问图片_第3张图片
[4] 背后的原理:
那么我们为什么能直接访问到该图片呢?这主要是跟部署的图片路径位置有关
我们打开项目打包后的路径会发现,0.jpg是放在了target目录下的classes/static/img/0.jpg目录下,我们访问localhost:8080/ 其实就是到这个的类路径下进行寻找(static默认也被认定为classpath), 这样我们直接访问 img/0.jpg,就能直接找到对应的文件了。(之后我们关于服务器上的内容都是通过类似的方式进行寻找的)
使用SpringBoot访问图片_第4张图片

2. 通过html页面显示当前的图片

[1] 编写controller 层文件
由于我们前面导入了template模板,所以我们编写的@Controller类可以通过字符串跳转到前端页面(testimg.html)

package com.example.kcb02.controller;

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

/**
 * @Auther: Gs
 * @Date: 2020/5/29
 * @Description: com.example.kcb02.controller
 * @version: 1.0
 */
//测试图片显示
@Controller
public class TestimgController {

    @GetMapping("/testimg")
    public String getImg(){
        return "testimg";
    }

}

在templates下新建一个testimg.html文件


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>

<h1>测试图片h1>
<img src="../img/0.jpg" height="452" width="450"/>

body>
html>

这里我们访问 http://localhost:8080/testimg 就可以显示出图片了
使用SpringBoot访问图片_第5张图片

你可能感兴趣的:(Spring,Boot)