使用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进行路径的直接映射)

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

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文件

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

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

</body>
</html>

这里我们访问 http://localhost:8080/testimg 就可以显示出图片了
在这里插入图片描述

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值