基于thymeleaf实现数据库图片展示到浏览器表格

一、编写数据库表

下面创建一个花店的商品表,pic字段用于存放图片

CREATE TABLE `pms_product`  (
  `id` bigint(0) NOT NULL AUTO_INCREMENT,
  `name` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '商品名称',
  `pic` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '图片',
  `sale` int(0) NULL DEFAULT NULL COMMENT '销量',
  `price` decimal(10, 2) NULL DEFAULT NULL COMMENT '价格',
  `description` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '商品描述',
  `stock` int(0) NULL DEFAULT NULL COMMENT '库存',
  `weight` decimal(10, 2) NULL DEFAULT NULL COMMENT '商品重量,默认为克',
  `brand_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '品牌名称',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

存入相应数据
在这里插入图片描述

二、编写SpringBoot业务代码

  1. pom.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.web</groupId>
  <artifactId>images</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>images</name>
  <description>images</description>
  <properties>
    <java.version>1.8</java.version>
  </properties>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.6</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>
  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>2.2.2</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <scope>runtime</scope>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.11.0</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>
  </dependencies>
  
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
          <excludes>
            <exclude>
              <groupId>org.projectlombok</groupId>
              <artifactId>lombok</artifactId>
            </exclude>
          </excludes>
        </configuration>
      </plugin>
    </plugins>
  </build>
  
</project>
  1. application.yml配置,同时配置启动类扫描mapper接口
server:
  port: 2000

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/demo?serverTimezone=UTC
    username: root
    password: 123456

mybatis:
  mapper-locations: classpath:/mapper/*.xml
package com.web;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.web.mapper")
public class ImagesApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(ImagesApplication.class, args);
    }
    
}
  1. 编写包结构
    在这里插入图片描述

  2. 编写实体类

package com.web.entity;

import lombok.Data;

@Data
public class Product {
    
    private Integer id;
    private String name;
    private String pic;
    private Integer sale;
    private Double price;
    private String description;
    private Integer stock;
    private Double weight;
    private String brand_name;
    
}
  1. 编写控制层
package com.web.controller;

import com.web.entity.Product;
import com.web.service.impl.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class ImagesController {

    @Resource
    private ProductService productService;

    /**
     * 查询所有商品,然后放到model中
     * @param model
     * @return
     */
    @GetMapping("/list")
    public String list(Model model){
        List<Product> productList = productService.list();
        model.addAttribute("productList", productList);
        return "list";
    }

}
  1. 编写service层
package com.web.service.impl;

import com.web.entity.Product;

import java.util.List;

public interface ProductService {
    List<Product> list();
}

  1. 编写services实现层
package com.web.service.impl;

import com.web.entity.Product;
import com.web.mapper.ProductMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductMapper productMapper;

    @Override
    public List<Product> list() {
        return productMapper.list();
    }
}
  1. 编写mapper接口
package com.web.mapper;

import com.web.entity.Product;

import java.util.List;

public interface ProductMapper {

    List<Product> list();

}
  1. 编写持久层
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.web.mapper.ProductMapper">
  
  <select id="list" resultType="com.web.entity.Product">
    select * from pms_product
  </select>
  
</mapper>

三、编写图片上传功能及展示

  1. 上传图片功能
package com.web.controller;

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("file")
public class FileController {

	@RequestMapping("download")
	public ResponseEntity<byte[]> download(String filename) {
		// 设置编码
		try {
			String newFileName = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
			// 文件所在路径
			String path = "D:\\";
			// 文件下载的全路径
			String downPath = path + filename;
			// 生成下载的文件
			File file = new File(downPath);
			// 设置HttpHeaders,使得浏览器响应下载
			HttpHeaders headers = new HttpHeaders();
			// 给浏览器设置下载文件名
			headers.setContentDispositionFormData("attachment", newFileName);
			// 浏览器响应方式
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			// 把文件以二进制格式响应给浏览器
			ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
					headers, HttpStatus.OK);
			return responseEntity;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
  1. 图片展示
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>

        <table border="1">
            <tr>
                <td>编号</td>
                <td>名称</td>
                <td>图片</td>
                <td>销量</td>
                <td>价格</td>
                <td>描述</td>
                <td>库存</td>
                <td>重量</td>
                <td>品牌名称</td>
            </tr>
            <tr th:each="product : ${productList}">
                <td th:text="${product.getId()}"></td>
                <td th:text="${product.getName()}"></td>
                <td>
                    <img th:src="@{/file/download?(filename=${product.getPic()})}" alt="" style="width: 150px; height: 150px">
                </td>
                <td th:text="${product.getSale()}"></td>
                <td th:text="${product.getPrice()}"></td>
                <td th:text="${product.getDescription()}"></td>
                <td th:text="${product.getStock()}"></td>
                <td th:text="${product.getWeight()}"></td>
                <td th:text="${product.getBrand_name()}"></td>
            </tr>
        </table>

    </body>
</html>

完整目录

在这里插入图片描述

四、最终效果

在这里插入图片描述

五、总结

  1. 文件路径总结:
    1. 图片在本地的保存路径:D:\img
    2. 表中pic字段保存图片的路径:img/图片名
    3. FileController中文件上传路径:String path = "D:\\";

总结为:FileController中图片上传路径和表中图片保存路径加起来是图片的绝对路径

  1. FileController中实现图片上传方法

  2. 结合thymeleaf展示图片:th:src="@{/file/download?(filename=${product.getPic()})}"

  3. 其他的业务代码都是比较常见的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值