当前位置:网站首页>基于thymeleaf实现数据库图片展示到浏览器表格
基于thymeleaf实现数据库图片展示到浏览器表格
2022-04-23 05:42:00 【ShuangTwo】
一、编写数据库表
下面创建一个花店的商品表,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业务代码
- 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>
- 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);
}
}
-
编写包结构
-
编写实体类
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;
}
- 编写控制层
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";
}
}
- 编写service层
package com.web.service.impl;
import com.web.entity.Product;
import java.util.List;
public interface ProductService {
List<Product> list();
}
- 编写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();
}
}
- 编写mapper接口
package com.web.mapper;
import com.web.entity.Product;
import java.util.List;
public interface ProductMapper {
List<Product> list();
}
- 编写持久层
<?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>
三、编写图片上传功能及展示
- 上传图片功能
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;
}
}
}
- 图片展示
<!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>
完整目录
四、最终效果
五、总结
- 文件路径总结:
- 图片在本地的保存路径:
D:\img
- 表中pic字段保存图片的路径:
img/图片名
- FileController中文件上传路径:
String path = "D:\\";
- 图片在本地的保存路径:
总结为:FileController中图片上传路径和表中图片保存路径加起来是图片的绝对路径
-
FileController中实现图片上传方法
-
结合thymeleaf展示图片:
th:src="@{/file/download?(filename=${product.getPic()})}"
-
其他的业务代码都是比较常见的
版权声明
本文为[ShuangTwo]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43356538/article/details/124085450
边栏推荐
- 实体中list属性为空或者null,设置为空数组
- Find the number of "blocks" in the matrix (BFS)
- mysql sql优化之Explain
- Map对象 map.get(key)
- DWSurvey是一个开源的调查问卷系统。解决无法运行问题,修改bug。
- Strategy for improving the conversion rate of independent stations | recovering abandoned users
- 提升Facebook触及率和互动率攻略 | 智能客服帮您抓住用户的心
- The role of brackets' [] 'in the parameter writing method in MDN documents
- Relative reference and absolute reference of Excel
- POI exports to excel, and the same row of data is automatically merged into cells
猜你喜欢
2-軟件設計原則
SQL注入
Radar equipment (greedy)
SQL statement simple optimization
Pytorch deep learning practice_ 11 convolutional neural network
Generation of straightening body in 3D slicer
Duplicate key update in MySQL
Hongji cyclone RPA provides technical support for Guojin securities and realizes process automation in more than 200 business scenarios
Frequently asked interview questions - 2 (computer network)
基于ssm 包包商城系统
随机推荐
MySQL query uses \ g, column to row
Sword finger offer II 022 The entry node of the link in the linked list
AcWing 1096. Detailed notes of Dungeon Master (3D BFS) code
Hongji micro classroom | cyclone RPA's "flexible digital employee" actuator
创建线程的三种方式
deep learning object detection
Excel sets row and column colors according to cell contents
Markdown syntax support test
idea插件---背景播放歌曲
字符识别easyocr
STL function library
Error 2003 (HY000) when Windows connects MySQL: can't connect to MySQL server on 'localhost' (10061)
opensips(1)——安装opensips详细流程
MySQL transaction
mysql中duplicate key update
Hongji cyclone RPA provides technical support for Guojin securities and realizes process automation in more than 200 business scenarios
JDBC工具类封装
MySQL lock mechanism
Relative reference and absolute reference of Excel
xxl-job采坑指南xxl-rpc remoting error(connect timed out)