当前位置:网站首页>Implementation of displaying database pictures to browser tables based on thymeleaf
Implementation of displaying database pictures to browser tables based on thymeleaf
2022-04-23 05:57:00 【ShuangTwo】
One 、 Write database tables
Now create a florist's product table ,pic Field is used to store pictures
CREATE TABLE `pms_product` (
`id` bigint(0) NOT NULL AUTO_INCREMENT,
`name` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ' Name of commodity ',
`pic` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ' picture ',
`sale` int(0) NULL DEFAULT NULL COMMENT ' sales ',
`price` decimal(10, 2) NULL DEFAULT NULL COMMENT ' Price ',
`description` text CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT ' Commodity Description ',
`stock` int(0) NULL DEFAULT NULL COMMENT ' stock ',
`weight` decimal(10, 2) NULL DEFAULT NULL COMMENT ' The weight of the goods , The default is gram ',
`brand_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ' The brand name ',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
Store corresponding data
Two 、 To write SpringBoot Business code
- pom.xml To configure
<?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 To configure , At the same time, configure and start class scanning mapper Interface
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);
}
}
-
Write package structure
-
Write entity class
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;
}
- Write control layer
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;
/** * Check all products , Then put model in * @param model * @return */
@GetMapping("/list")
public String list(Model model){
List<Product> productList = productService.list();
model.addAttribute("productList", productList);
return "list";
}
}
- To write service layer
package com.web.service.impl;
import com.web.entity.Product;
import java.util.List;
public interface ProductService {
List<Product> list();
}
- To write services Implementation layer
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();
}
}
- To write mapper Interface
package com.web.mapper;
import com.web.entity.Product;
import java.util.List;
public interface ProductMapper {
List<Product> list();
}
- Write persistence layer
<?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>
3、 ... and 、 Write picture upload function and display
- Upload image function
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) {
// Set encoding
try {
String newFileName = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
// File path
String path = "D:\\";
// Full path of file download
String downPath = path + filename;
// Generate downloaded files
File file = new File(downPath);
// Set up HttpHeaders, Make the browser respond to download
HttpHeaders headers = new HttpHeaders();
// Set the download file name for the browser
headers.setContentDispositionFormData("attachment", newFileName);
// How the browser responds
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// Respond the file to the browser in binary format
ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.OK);
return responseEntity;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
- Pictures show
<!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> Number </td>
<td> name </td>
<td> picture </td>
<td> sales </td>
<td> Price </td>
<td> describe </td>
<td> stock </td>
<td> weight </td>
<td> The brand name </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>
Complete directory
Four 、 Final effect
5、 ... and 、 summary
- File path summary :
- The local save path of the picture :
D:\img
- In the table pic Field to save the path of the picture :
img/ Picture name
- FileController File upload path in :
String path = "D:\\";
- The local save path of the picture :
Summed up in :FileController The image upload path in and the image save path in the table add up to the absolute path of the image
-
FileController Image upload method in
-
combination thymeleaf Show pictures :
th:src="@{/file/download?(filename=${product.getPic()})}"
-
Other business codes are common
版权声明
本文为[ShuangTwo]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230541367733.html
边栏推荐
- JVM series (3) -- memory allocation and recycling strategy
- Ptorch learning record (XIII): recurrent neural network
- 图像恢复论文简记——Uformer: A General U-Shaped Transformer for Image Restoration
- Pytoch learning record (x): data preprocessing + batch normalization (BN)
- You cannot access this shared folder because your organization's security policy prevents unauthenticated guests from accessing it
- JDBC操作事务
- Latex快速入门
- 建表到页面完整实例演示—联表查询
- Multithreading and high concurrency (1) -- basic knowledge of threads (implementation, common methods, state)
- Traitement des séquelles du flux de Tensor - exemple simple d'enregistrement de torche. Utils. Données. Dataset. Problème de dimension de l'image lors de la réécriture de l'ensemble de données
猜你喜欢
解决报错:ImportError: IProgress not found. Please update jupyter and ipywidgets
Dva中在effects中获取state的值
开发环境 EAS登录 license 许可修改
线程的底部实现原理—静态代理模式
LDCT图像重建论文——Eformer: Edge Enhancement based Transformer for Medical Image Denoising
Font shape `OMX/cmex/m/n‘ in size <10.53937> not available (Font) size <10.95> substituted.
sklearn之 Gaussian Processes
Multithreading and high concurrency (1) -- basic knowledge of threads (implementation, common methods, state)
Pyqy5 learning (4): qabstractbutton + qradiobutton + qcheckbox
Fundamentals of digital image processing (Gonzalez) I
随机推荐
建表到页面完整实例演示—联表查询
MySQL lock mechanism
Record a project experience and technologies encountered in the project
Pytorch learning record (III): structure of neural network + using sequential and module to define the model
多线程与高并发(3)——synchronized原理
Pyqy5 learning (4): qabstractbutton + qradiobutton + qcheckbox
框架解析2.源码-登录认证
EditorConfig
类的加载与ClassLoader的理解
C3P0数据库连接池使用
深度学习基础——简单了解meta learning(来自李宏毅课程笔记)
Dva中在effects中获取state的值
Software architecture design - software architecture style
Pyemd installation and simple use
JVM系列(3)——内存分配与回收策略
实操—Nacos安装与配置
Getting started with JDBC \ getting a database connection \ using Preparedstatement
ValueError: loaded state dict contains a parameter group that doesn‘t match the size of optimizer‘s
Development environment EAS login license modification
String notes