实体类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仅供参考,也希望老铁们多给些意见,让它更加的完美,最后希望老铁们可以告诉我怎么才能把图片上传到服务中去,因为在网没找着,拜托啦。