项目需求:
- 用户登录,
- 用户可以选择注册
- 用户登录之后在主页面列表显示所有的已上传的文件,如果是图片,则可以显示是图片
- 在文件列表 功能区 中显示 下载、在线打开,然后下载次数
- 同时在主页面中有上传功能,上传的目录要根据日期每天创建一个文件夹(文件夹名命名规则:“yyyy-MM-dd”),上传完成后跳转到主页面,并且显示列表已经上传的所有文件,
项目规范
- 项目统一命名为:file_xxx
- 包名统一规范
项目中的总文件夹(webroot)
- 建立file作为上传下载的总文件夹
- 根据日期在根目录文件夹每天创建不同文件夹
- 简单创建两张不同的页面(登录和用户主页)
注意项目所有的编码格式统一为utf-8
开始:
(一) 创建一个spring项目
删除
添加lombok版本号,同时注释掉test的功能,所以此时的/src/test
不能再使用
springboot打包跳过测试,在pom.xml 添加
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
环境准备好,准备开发前端界面
(二)首先在templates下面创建两个页面(登录页面和主页)
(登录界面的代码:)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<h1>欢迎访问用户文件管理系统</h1>
<form th:action="@{/user/login}" method="post">
username: <input type="text" name="username"/> <br>
password: <input type="text" name="password"/> <br>
<input type="submit" value="登录">
</form>
</body>
</html>
主页的详情代码:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>用户文件列表页面</title>
<script th:src="@{/js/jquery-3.4.1.min.js}"></script>
<script>
$(function(){
var time;
$("#start").click(function(){
console.log("开启定时更新.........");
time = setInterval(function () {
$.get("[[@{/file/findAllJSON}]]", function (res) {
//遍历
$.each(res, function (index, file) {
$("#" + file.id).text(file.downcounts);
})
});
}, 3000);
});
$("#stop").click(function () {
console.log("关闭定时更新");
clearInterval(time);
});
});
</script>
</head>
<body>
<h1>欢迎: <span th:if="${session.user!=null}" th:text="${session.user.username}"/></h1>
<h3>文件列表:</h3>
<button id="start">开启定时更新</button>
<button id="stop">结束定时更新</button>
<table border="1px">
<tr>
<th>ID</th>
<th>文件原始名称</th>
<th>文件的新名称</th>
<th>文件后缀</th>
<th>存储路径</th>
<th>文件大小</th>
<th>类型</th>
<th>是否是图片</th>
<th>下载次数</th>
<th>上传时间</th>
<th>操作</th>
</tr>
<tr th:each="file,fileStat:${files}">
<td><span th:text="${file.id}"/></td>
<td><span th:text="${file.oldFileName}"/></td>
<td><span th:text="${file.newFileName}"/></td>
<td><span th:text="${file.ext}"/></td>
<td><span th:text="${file.path}"/></td>
<td><span th:text="${file.size}"/></td>
<td><span th:text="${file.type}"/></td>
<td>
<img th:if="${file.isImg}=='是'" style="width: 100px;height: 40px;" th:src="${#servletContext.contextPath}+${file.path}+'/'+${file.newFileName}" alt="">
<span th:if="${file.isImg}!='是'" th:text="${file.isImg}"/>
</td>
<td th:id="${file.id}"><span th:text="${file.downcounts}"/></td>
<td><span th:text="${#dates.format(file.uploadTime,'yyyy-MM-dd HH:mm:ss')}"/></td>
<td>
<a th:href="@{/file/download(id=${file.id})}">下载</a>
<a th:href="@{/file/download(id=${file.id},openStyle='inline')}">在线打开</a>
<a th:href="@{/file/delete(id=${file.id})}">删除</a>
</td>
</tr>
</table>
<hr>
<h3>上传文件:</h3>
<form th:action="@{/file/upload}" method="post" enctype="multipart/form-data">
<input type="file" name="input-up">
<input type="submit" value="上传文件">
</form>
</body>
</html>
此时前端的界面已经完成
(三) 接下来是创建两张数据表
用户表 和 文件上传表
/*
Navicat Premium Data Transfer
Source Server : localhost_3306
Source Server Type : MySQL
Source Server Version : 80018
Source Host : localhost:3306
Source Schema : ziyefiles
Target Server Type : MySQL
Target Server Version : 80018
File Encoding : 65001
Date: 16/05/2020 16:11:40
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for t_files
-- ----------------------------
DROP TABLE IF EXISTS `t_files`;
CREATE TABLE `t_files` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`oldFileName` varchar(300) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`newFileName` varchar(300) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`ext` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`path` varchar(300) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`size` varchar(300) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`type` varchar(150) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`isImg` varchar(8) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`downcounts` int(6) NULL DEFAULT NULL,
`uploadTime` datetime(0) NULL DEFAULT NULL,
`userId` int(8) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
INDEX `userId`(`userId`) USING BTREE,
CONSTRAINT `userId` FOREIGN KEY (`userId`) REFERENCES `t_user` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of t_files
-- ----------------------------
-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(8) NOT NULL,
`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of t_user
-- ----------------------------
SET FOREIGN_KEY_CHECKS = 1;
(四) 编辑spring的配置文件
注意首先要在pom.xml中添加阿里巴巴的镜像源
配置文件(application.properties文件)
spring.application.name=sfiles
# 当前应用的名字 这在微服务中十分重要
server.port=8989
# 服务器的访问端口号
server.servlet.context-path=/files
# 定义:应用的上下文路径,也可以称为项目路径,是构成url地址的一部分。
# server.servlet.context-path不配置时,默认为 / ,如:localhost:8080/xxxxxx
# 当server.servlet.context-path有配置时,
# 比如 /demo,此时的访问方式为localhost:8080/demo/xxxxxx
spring.thymeleaf.cache=false
# spring 和thymeleaf之间的模板缓冲 不开启
spring.thymeleaf.suffix=.html
#spring.thymeleaf.suffix = .html #构建URL时附加到查看名称的后缀。
spring.thymeleaf.encoding=UTF-8
# 模板编码
spring.thymeleaf.prefix=classpath:/templates/
# 代表着根目录文件的位置 默认就是这个设置
spring.resources.static-locations=classpath:/templates/,classpath:/static/,file:${upload.dir}
# 自定义静态资源位置,告诉Spring Boot应该在何处查找静态资源文件,这是一个列表性的配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# 阿里巴巴镜像源
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 数据库8.0 以上带cj 否则反之
spring.datasource.url=jdbc:mysql://localhost:3306/ziyefiles?characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
# 配置数据库
mybatis.mapper-locations=classpath:/com/ziye/files/mapper/*.xml
# 注意点:在classpath后面的 * 必不可少,缺少型号的话后面的通配符不起作用
mybatis.type-aliases-package=com.ziye.files
# mybatis放的位置
logging.level.root=info
# 输出日志等级
logging.level.com.baizhi.dao=debug
# 输出日志等级
upload.dir=/Users/chenyannan/files/
最后在main类中添加扫描dao层注解
由于刚才设置了启动不经过test所以要设置
现在可以启动服务:
(五) 编辑实体类、mapper映射配置文件、dao层(数据访问层)、service(业务层接口)、service层实现类
User实体类
package com.ziye.files.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
@Data
// 使用这个注解,就不用再去手写Getter,Setter,equals,canEqual,hasCode,toString等方法了,注解后在编译时会自动加进去
@AllArgsConstructor
// 使用后添加一个构造函数,该构造函数含有所有已声明字段属性参数
@NoArgsConstructor
//使用后创建一个无参构造函数
@ToString
//
@Accessors(chain=true)
//chain决定set方法是void类型还是返回this
public class User {
private Integer id;
private String username;
private String password;
}
UserFile实体类
package com.ziye.files.entity;
/**
* @Classname UserFile
* @Description TODO
* @Date 2020/5/17 13:55
* @Created by ziye
*/
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Accessors(chain=true)
public class UserFile {
private Integer id;
private String oldFileName;
private String newFileName;
private String ext;
private String path;
private String size;
private String type;
private String isImg;
private Integer downcounts;
private Date uploadTime;
private Integer userId; //用户外键
}```
#### user数据访问接口
```java
package com.ziye.files.dao;
import com.ziye.files.entity.User;
/**
* @Classname userDAO
* @Description TODO
* @Date 2020/5/17 13:55
* @Created by ziye
*/
public interface UserDAO {
User login(User user);
}
UserDao层
package com.ziye.files.dao;
import com.ziye.files.entity.User;
/**
* @Classname userDAO
* @Description TODO
* @Date 2020/5/17 13:55
* @Created by ziye
*/
public interface UserDAO {
User login(User user);
}
UserFileDao层
package com.ziye.files.dao;
import com.ziye.files.entity.UserFile;
import java.util.List;
public interface UserFileDAO {
//根据登录用户id获取用户的文件列表
List<UserFile> findByUserId(Integer id);
//保存用户的文件记录
void save(UserFile userFile);
//根据文件id获取文件信息
UserFile findById(String id);
//根据id更新下载次数
void update(UserFile userFile);
//根据id删除记录
void delete(String id);
}
UserDao的mapper映射文件:
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ziye.files.dao.UserDAO">
<!--login-->
<!-- 1. id (必须配置)
id是命名空间中的唯一标识符,可被用来代表这条语句。
一个命名空间(namespace) 对应一个dao接口,
这个id也应该对应dao里面的某个方法(相当于方法的实现),因此id 应该与方法名一致 -->
<!-- 2. parameterType (可选配置, 默认为mybatis自动选择处理)
将要传入语句的参数的完全限定类名或别名, 如果不配置,mybatis会通过ParameterHandler 根据参数类型默认选择合适的typeHandler进行处理
parameterType 主要指定参数类型,可以是int, short, long, string等类型,也可以是复杂类型(如对象) -->
<!-- 要点1: #是将传入的值当做字符串的形式
使用#可以很大程度上防止 sql 注入。 (语句的拼接)
#{ }:解析为一个 JDBC 预编译语句(prepared statement)的参数标记符。预编译,重复
利用,效率高
-->
<select id="login" parameterType="User" resultType="User">
select id,username,password
from t_user
where username=#{username}
and password = #{password}
</select>
</mapper>
UserFile的mapper映射文件:
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ziye.files.dao.UserFileDAO">
<!--根据用户id查询当前用户的文件信息-->
<select id="findByUserId" parameterType="Integer" resultType="UserFile">
select id,oldFileName,newFileName,ext,path,size,type,isImg,downcounts,uploadTime,userId
from t_files
where userId=#{id}
</select>
<!--保存文件信息-->
<!-- 设置为 true 时,表示如果插入的表id以自增列为主键,
则允许 JDBC 支持自动生成主键,并可将自动生成的主键id返回。-->
<insert id="save" parameterType="UserFile" useGeneratedKeys="true" keyProperty="id">
insert into t_files
values (#{id},#{oldFileName},#{newFileName},
#{ext}, #{path},#{size},#{type},
#{isImg},#{downcounts}, #{uploadTime},#{userId})
</insert>
<!--根据id获取文件信息-->
<select id="findById" parameterType="String" resultType="UserFile">
select id,oldFileName,newFileName,ext,path,size,type,isImg,downcounts,uploadTime,userId
from t_files
where id = #{id}
</select>
<!--更新下载次数-->
<update id="update" parameterType="UserFile" >
update t_files set downcounts=#{downcounts} where id=#{id}
</update>
<!--根据id删除记录-->
<delete id="delete" parameterType="String">
delete from t_files where id=#{id}
</delete>
</mapper>
UserService接口
package com.ziye.files.service;
import com.ziye.files.entity.User;
/**
* @Classname UserService
* @Description TODO
* @Date 2020/5/17 14:37
* @Created by ziye
*/
// MVC本身不属于设计模式的一种,它描述的是一种结构,最终目的达到解耦,
// 解耦说的意思是你更改某一层代码,不会影响我其他层代码,
// 如果你会像spring这样的框架,你会了解面向接口编程,表示层调用控制层,
// 控制层调用业务层,业务层调用数据访问层。
public interface UserService {
User login(User user);
}
UserService接口实现
package com.ziye.files.service;
import com.ziye.files.dao.UserDAO;
import com.ziye.files.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class UserServciceImpl implements UserService {
@Autowired
private UserDAO userDAO;
@Override
@Transactional(propagation = Propagation.SUPPORTS)
public User login(User user) {
return userDAO.login(user);
}
}
UserFileService接口
package com.ziye.files.service;
import com.ziye.files.entity.UserFile;
import java.util.List;
public interface UserFileService {
List<UserFile> findByUserId(Integer id);
void save(UserFile userFile);
UserFile findById(String id);
void update(UserFile userFile);
void delete(String id);
}
UserFileService接口实现
package com.ziye.files.service;
import com.ziye.files.dao.UserFileDAO;
import com.ziye.files.entity.UserFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
@Service
@Transactional
public class UserFileServiceImpl implements UserFileService {
@Autowired
private UserFileDAO userFileDAO;
@Override
public List<UserFile> findByUserId(Integer id) {
return userFileDAO.findByUserId(id);
}
@Override
public void delete(String id) {
userFileDAO.delete(id);
}
@Override
public void update(UserFile userFile) {
userFileDAO.update(userFile);
}
@Override
public UserFile findById(String id) {
return userFileDAO.findById(id);
}
@Override
public void save(UserFile userFile) {
//userFile.setIsImg()? //是否是图片 解决方案: 当类型中含有image时说明当前类型一定为图片类型
String isImg = userFile.getType().startsWith("image")?"是":"否";
userFile.setIsImg(isImg);
userFile.setDowncounts(0);
userFile.setUploadTime(new Date());
userFileDAO.save(userFile);
}
}
编辑控制层
控制访问登录页面:
package com.ziye.files.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@GetMapping("/")
public String toLogin(){
return "login";
}
}
登录校验页面
package com.ziye.files.controller;
import com.ziye.files.entity.User;
import com.ziye.files.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {
@Autowired
private UserService userService;
/**
* 登录方法
*/
@PostMapping("/login")
public String login(User user, HttpSession session){
User userDB = userService.login(user);
if(userDB!=null){
session.setAttribute("user",userDB);
return "redirect:/file/showAll";
}else{
return "redirect:/index";
}
}
}
控制文件管理页面
package com.ziye.files.controller;
import com.ziye.files.entity.User;
import com.ziye.files.entity.UserFile;
import com.ziye.files.service.UserFileService;
import com.ziye.files.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.transform.Source;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("/file")
public class FileController {
@Autowired
private UserFileService userFileService;
// @Value("${upload.dir}")
// private String uploadPath;
/**
* 返回当前用户的所有文件列表---json格式数据
*/
// @GetMapping("findAllJSON")
// @ResponseBody
// public List<UserFile> findAllJSON(HttpSession session, Model model) {
// //在登录的session中获取用户的id
// User user = (User) session.getAttribute("user");
// //根据用户id查询有的文件信息
// List<UserFile> userFiles = userFileService.findByUserId(user.getId());
// return userFiles;
// }
/**
* 删除文件信息
*/
@GetMapping("delete")
public String delete(String id) throws FileNotFoundException {
//根据id查询信息
UserFile userFile = userFileService.findById(id);
//删除文件
String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static" + userFile.getPath();
File file = new File(realPath, userFile.getNewFileName());
if(file.exists())file.delete();//立即删除
//删除数据库中记录
userFileService.delete(id);
return "redirect:/file/showAll";
}
/**
* 文件下载
*/
// @GetMapping("download")
// public void download(String openStyle, String id, HttpServletResponse response) throws IOException {
// //获取打开方式
// openStyle = openStyle == null ? "attachment" : openStyle;
// //获取文件信息
// UserFile userFile = userFileService.findById(id);
// //点击下载链接更新下载次数
// if ("attachment".equals(openStyle)) {
// userFile.setDowncounts(userFile.getDowncounts() + 1);
// userFileService.update(userFile);
// }
// //根据文件信息中文件名字 和 文件存储路径获取文件输入流
// String realpath = ResourceUtils.getURL("classpath:").getPath() + "/static" + userFile.getPath();
// //获取文件输入流
// FileInputStream is = new FileInputStream(new File(realpath, userFile.getNewFileName()));
// //附件下载
// response.setHeader("content-disposition", openStyle + ";fileName=" + URLEncoder.encode(userFile.getOldFileName(), "UTF-8"));
// //获取响应输出流
// ServletOutputStream os = response.getOutputStream();
// //文件拷贝
// IOUtils.copy(is, os);
// IOUtils.closeQuietly(is);
// IOUtils.closeQuietly(os);
// }
/**
* 上传文件处理 并保存文件信息到数据库中
*/
// @PostMapping("upload")
// public String upload(MultipartFile aaa, HttpSession session) throws IOException {
// //获取上传文件用户id
// User user = (User) session.getAttribute("user");
// //获取文件原始名称
// String oldFileName = aaa.getOriginalFilename();
//
// //获取文件后缀
// String extension = "." + FilenameUtils.getExtension(aaa.getOriginalFilename());
//
// //生成新的文件名称
// String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;
//
// //文件大小
// Long size = aaa.getSize();
//
// //文件类型
// String type = aaa.getContentType();
//
// //处理根据日期生成目录
// //String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files";
// String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
// String dateDirPath = uploadPath + "/files/" + dateFormat;
// File dateDir = new File(dateDirPath);
// if (!dateDir.exists()) dateDir.mkdirs();
//
// //处理文件上传
// aaa.transferTo(new File(dateDir, newFileName));
//
// //将文件信息放入数据库保存
// UserFile userFile = new UserFile();
// userFile.setOldFileName(oldFileName).setNewFileName(newFileName).setExt(extension).setSize(String.valueOf(size))
// .setType(type).setPath("/files/" + dateFormat).setUserId(user.getId());
// userFileService.save(userFile);
//
// return "redirect:/file/showAll";
// }
/**
* 展示所有文件信息
*/
@GetMapping("/showAll")
public String findAll(HttpSession session, Model model) {
// //在登录的session中获取用户的id
// User user = (User) session.getAttribute("user");
//
// //根据用户id查询有的文件信息
// List<UserFile> userFiles = userFileService.findByUserId(user.getId());
// //存入作用域中
// model.addAttribute("files", userFiles);
System.out.println("进入");
return "showAll";
}
}
先在user表中创建一个用户,然后就可以访问http://localhost:8989/files/
登录成功