使用spring boot+JPA实现增、删、查、改和上传图片的小demo,把它记录下来,防止以后忘记了

xiaoxiao2021-02-28  26

我的工程目录

一、前端的页面

list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <link rel="stylesheet" href="/css/bootstrap.css"></link> </head> <body> <div class="with:80%"> <table class="table table-hover"> <thead> <tr align="center"> <td colspan="9"> <form action="/listall" method="post"> <label>查询条件:</label> <input type="text" name="userName" id="userName" placeholder="输入姓名"> <input type="submit" value="查询" class="btn btn-info" /> </form> </td> </tr> <tr> <th>编号</th> <th>用户名</th> <th>密码</th> <th>邮箱</th> <th>头像</th> <th>编辑</th> <th>删除</th> </tr> </thead> <tbody> <c:set var="index" value="0" /> <c:forEach var="i" items="${list}" > <c:set var="index" value="${index+1}" /> <tr> <th >${index}</th> <td >${i.userName}</td> <td >${i.passWord}</td> <td >${i.email}</td> <td ><img src="/upload/${i.filepath }" width="100" height="100"></td> <td><a href="/toEdit?id=${i.id }" class="btn btn-info">edit</a></td> <td><a href="javascript:void(0)" οnclick="del(${i.id })" class="btn btn-info">delete</a></td> </tr> </c:forEach> </tbody> </table> <script type="text/javascript"> function del(id){ if(confirm("确认删除id="+id)) location.href="/del?id="+id; } </script> </div> <div class="form-group"> <div class="col-sm-2 control-label"> <a href="userAdd.jsp" class="btn btn-info">添加</a> </div> </div> </body> </html>
userAdd.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <link rel="stylesheet" href="/css/bootstrap.css"></link> </head> <body class="container"> <br/> <h1>用户添加</h1> <br/><br/> <div class="with:80%"> <form class="form-horizontal" action="/add" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="userName" class="col-sm-2 control-label">用户名</label> <div class="col-sm-10"> <input type="text" class="form-control" name="userName" id="userName" placeholder="userName"/> </div> </div> <div class="form-group"> <label for="password" class="col-sm-2 control-label" >密码</label> <div class="col-sm-10"> <input type="password" class="form-control" name="passWord" id="passWord" placeholder="passWord"/> </div> </div> <div class="form-group"> <label for="age" class="col-sm-2 control-label">邮箱</label> <div class="col-sm-10"> <input type="text" class="form-control" name="email" id="email" placeholder="email"/> </div> </div> <div class="form-group"> <label for="filepath" class="col-sm-2 control-label">头像</label> <img width="100" height="100" id="preview"> <input type="file" name="file" id="imgPicker"/> </div> <script type="text/javascript"> document .querySelector('#imgPicker') .addEventListener('change', function(){ //当没选中图片时,清除预览 if(this.files.length === 0){ document.querySelector('#preview').src = ''; return; } //实例化一个FileReader var reader = new FileReader(); reader.onload = function (e) { //当reader加载时,把图片的内容赋值给 document.querySelector('#preview').src = e.target.result; }; //读取选中的图片,并转换成dataURL格式 reader.readAsDataURL(this.files[0]); }, false); </script> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input type="submit" value="提交" class="btn btn-info" />       <input type="reset" value="重置" class="btn btn-info" /> </div> </div> </form> </div> </body> </html>
userEdit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <link rel="stylesheet" href="/css/bootstrap.css"></link> </head> <body class="container"> <br/> <h1>用户编辑</h1> <br/><br/> <div class="with:80%"> <form class="form-horizontal" action="/add" method="post" enctype="multipart/form-data"> <input type="hidden" name="id" value="${user.id }"/> <div class="form-group"> <label for="userName" class="col-sm-2 control-label">用户名</label> <div class="col-sm-10"> <input type="text" class="form-control" name="userName" value="${user.userName }" id="userName" placeholder="userName"/> </div> </div> <div class="form-group"> <label for="password" class="col-sm-2 control-label" >密码</label> <div class="col-sm-10"> <input type="password" class="form-control" name="passWord" value="${user.passWord }" id="passWord" placeholder="passWord"/> </div> </div> <div class="form-group"> <label for="age" class="col-sm-2 control-label">邮箱</label> <div class="col-sm-10"> <input type="text" class="form-control" name="email" value="${user.email }" id="email" placeholder="email"/> </div> </div> <div class="form-group"> <label for="filepath" class="col-sm-2 control-label">头像</label> <img width="100" height="100" id="preview" src="/upload/${user.filepath }"> <input type="file" name="file" id="imgPicker"/> </div> <script type="text/javascript"> document .querySelector('#imgPicker') .addEventListener('change', function(){ //当没选中图片时,清除预览 if(this.files.length === 0){ document.querySelector('#preview').src = ''; return; } //实例化一个FileReader var reader = new FileReader(); reader.onload = function (e) { //当reader加载时,把图片的内容赋值给 document.querySelector('#preview').src = e.target.result; }; //读取选中的图片,并转换成dataURL格式 reader.readAsDataURL(this.files[0]); }, false); </script> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input type="submit" value="保存" class="btn btn-info" />       <a href="/list" class="btn btn-info">返回</a> </div> </div> </form> </div> </body> </html>

二、后台

实体类user:

package com.example.demo.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="t_user") public class User implements Serializable{ /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue private Integer id; @Column(name="username") private String userName; @Column(name="password") private String passWord; @Column(name="email") private String email; @Column(name="filepath") private String filepath; public User() { super(); } public String getFilepath() { return filepath; } public void setFilepath(String filepath) { this.filepath = filepath; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassWord() { return passWord; } public void setPassWord(String passWord) { this.passWord = passWord; } }

dao层:

package com.example.demo.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import com.example.demo.entity.User; public interface IUserRepository extends JpaRepository<User, Long>{ User findById(int i); @Query("select u from User u where u.email=?1") User findByEmail(String email); @Query("select u from User u where u.userName like ?1 order by u.userName desc") List<User> listByName(String name); }

实现部分直接放在了controller层了

package com.example.demo.view; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.example.demo.dao.IUserRepository; import com.example.demo.entity.User; @Controller public class IndexContorller { @Autowired private IUserRepository userRepository; @RequestMapping(value = "/index123",method = RequestMethod.GET) public String index() { return "redirect:list"; } @RequestMapping("/listall") public String listAll(User user,Model model) { String str="%"+user.getUserName()+"%"; List<User> list = userRepository.listByName(str); model.addAttribute("list", list); return "list"; } @RequestMapping("/list") public String list(Model model) { List<User> list = userRepository.findAll(); model.addAttribute("list", list); return "list"; } @RequestMapping("/add") public String add(User model,@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException { /*if (file.isEmpty()) { userRepository.save(model); return "redirect:list"; }else { //文件名 String fileName = file.getOriginalFilename(); //重命名 fileName = UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf(".")); //文件夹路径 String path = request.getSession().getServletContext() .getRealPath("upload"); System.out.println(path); byte[] bytes = file.getBytes(); Path path1 = Paths.get(path+"/"+fileName); Files.write(path1, bytes); model.setFilepath(fileName); userRepository.save(model); return "redirect:list"; }*/ if (!file.isEmpty()) { String str="src/main/resources/static/upload/"; //String str="C:/Users/DELL/Desktop/ELK/upload/"; String fileName = file.getOriginalFilename(); //重命名 fileName = UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf(".")); //File saveFile = new File(request.getSession().getServletContext().getRealPath("/upload/") + fileName); File saveFile = new File(str + fileName); if (!saveFile.getParentFile().exists()) { saveFile.getParentFile().mkdirs(); } BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile)); out.write(file.getBytes()); out.flush(); out.close(); model.setFilepath(fileName); userRepository.save(model); return "redirect:list"; } else { userRepository.save(model); return "redirect:list"; } } @RequestMapping("/toEdit") public String toEdit(User u,Model model) { User user=userRepository.findById(u.getId()); model.addAttribute("user", user); return "userEdit"; } @RequestMapping("/del") public String del(User u,Model model) { User user=userRepository.findById(u.getId()); userRepository.delete(user); return "redirect:list"; } }

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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>springboot-test</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot-test</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

application.properties文件:

spring.datasource.url=jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=UTF-8 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.sql-script-encoding=utf-8 #spring.http.encoding.force=true #spring.jpa.database = MYSQL spring.jpa.properties.hibernate.hbm2ddl.auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.show-sql= true #mybatis.type-aliases-package= #spring.redis.database=0 #spring.redis.host=192.168.0.58 #spring.redis.port=6379 #spring.redis.password= #spring.redis.jedis.pool.max-active=8 #spring.redis.jedis.pool.max-idle=8 #spring.redis.jedis.pool.max-wait=-1 #spring.redis.jedis.pool.min-idle=0 #spring.redis.timeout=0 #页面的前后缀 spring.mvc.view.prefix=/ spring.mvc.view.suffix=.jsp

启动入口类,访问http://localhost:8080/index123,页面效果如图:

总的来说,功能已全部实现了,但是我知道它还是不完美的,还有代码不够优雅。还有一个小问题,就是我上传文件是放在项目中的静态资源文件中,所以在添加成功之后返回list页面的时候,它的图片是显示不出来的,需要你手动去刷新项目后再刷新页面才显示。这个小demo仅供参考,也希望老铁们多给些意见,让它更加的完美,最后希望老铁们可以告诉我怎么才能把图片上传到服务中去,因为在网没找着,拜托啦。

转载请注明原文地址: https://www.6miu.com/read-2300334.html

最新回复(0)