基于javaweb+mysql的springboot+jpa网盘系统设计和实现(javaweb+springboot+ssm+jpa+thymeleaf+html+maven)
私信源码获取及调试交流
运行环境
Java≥8、MySQL≥5.7
开发工具
eclipse/idea/myeclipse/sts等均可配置运行
适用
课程设计,大作业,毕业设计,项目练习,学习演示等
功能说明
基于javaweb的SpringBoot+JPA网盘系统设计和实现(javaweb+springboot+ssm+jpa+thymeleaf+html+maven)
很多同学都有自己的网盘,方便存储一些java学习教程。该毕业设计实现了一个简易的网盘,包含文件上传和文件分享等功能。 后端技术采用了spring,spring mvc,JPA,前端采用了thymeleaf模板语言。整体业务功能相对不是太复杂,亮点是文件分享功能。
flag = false;
}
}
if (flag) {
j.setSuccess(true);
j.setMsg("删除成功!");
} else {
j.setMsg("删除失败!");
}
return j;
}
// 文件重命名 文件夹重命名时 老名字写path 新名字写newName oldName填@dir@
@RequestMapping(value = "/filerename", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg fileRename(String oldName, String newName, String path, HttpServletRequest request) {
if (path == null) {
path = "/";
}
ResponseMsg j = new ResponseMsg();
if (oldName.isEmpty() || newName.isEmpty()) {
j.setMsg("文件名字为空!");
return j;
}
// 获取用户名
String userName = WebUtil.getUserNameByRequest(request);
// 重命名文件
boolean b = fileService.userFileRename(oldName, newName, userName, path);
String saveFilePath = fileRootPath + userName + "/" + path;
String oldNameWithPath = saveFilePath + "/" + oldName;
File file = new File(oldNameWithPath);
if (b) {
j.setSuccess(true);
j.setMsg("重命名成功!");
logger.warn(j.getMsg());
} else if (!file.exists()) {
j.setMsg("没有重命名的权限!");
logger.warn(j.getMsg());
} else {
j.setMsg("重命名失败!");
logger.warn(j.getMsg());
}
return j;
}
// 文件夹创建
@RequestMapping(value = "/dircreate", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg dirCreate(String dirName, String path, HttpServletRequest request) {
ResponseMsg responseMsg = new ResponseMsg();
responseMsg.setSuccess(result);
if (result) {
responseMsg.setMsg(registerCode);
} else {
responseMsg.setMsg("生成注册码失败,请重新操作!");
}
return responseMsg;
}
}
/**
* 拦截配置
*
*
*/
public class WebInterceptor implements HandlerInterceptor {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
boolean flag = true;
if (handler instanceof HandlerMethod) {
String ip = request.getRemoteAddr();
long startTime = System.currentTimeMillis();
request.setAttribute("requestStartTime", startTime);
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
logger.warn("用户ip:" + ip + ",访问目标:" + method.getDeclaringClass().getName() + ":" + method.getName());
User user = (User) request.getSession().getAttribute("user");
/**
*
*/
@RestController
@RequestMapping(value = "/rest/pan")
public class PanRestV1Controller {
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 文件根目录
*/
@Value("${fileRootPath}")
private String root;
/**
* file业务处理bean
*/
@Autowired
private IFileService fileService;
/**
* 文件上传
*
* @param path 上传路径
* @param request Servlet3.0方式上传文件,获取parts
* @return result
*/
@RequestMapping("upload")
public ResponseMsg upload(@RequestParam String path, HttpServletRequest request) {
}
logger.warn("downloadLink:" + downloadLink);
boolean b = false;
ResponseMsg responseMsg = new ResponseMsg();
User user = (User) request.getSession().getAttribute("user");
if (user == null) {
responseMsg.setSuccess(false);
responseMsg.setMsg("未登录");
} else {
String userName = user.getUserName();
if (path == null) {
path = "/";
}
logger.warn(userName + " " + downloadLink + " " + path);
b = fileService.copyFileToMyPan(userName, downloadLink, path);
responseMsg.setSuccess(b);
if (b == false) {
responseMsg.setMsg("保存失败");
} else {
responseMsg.setMsg("保存成功");
}
}
return responseMsg;
}
/**
* 下载客户端的apk
* filename:下载apk的名字
* downloadPath:下载的文件夹,放在/root/pan/share目录中
*/
@RequestMapping(value = "/downloadApk", produces = {"application/json; charset=UTF-8"})
@ResponseBody
public ResponseMsg shareToMyPan(HttpServletRequest request, HttpServletResponse response, String filename,
String downloadPath) throws FileNotFoundException, UnsupportedEncodingException {
// 读到流中
// String filePath="F:/"+downloadPath+"/"+filename;//window上测试的路径
ResponseMsg responseMsg = new ResponseMsg();
String filePath = fileRootPath + downloadPath + "/" + filename;
InputStream inStream = new FileInputStream(filePath);
if (!new File(filePath).exists()) {
responseMsg.setMsg("找不到文件");
}
// 设置输出的格式
String agent = request.getHeader("user-agent");
String fileName4 = "";
if (agent.contains("Firefox")) {
fileName4 = new String(filename.getBytes(), "iso-8859-1");
} else {
//空格,(,),;,@,#,&,逗号在谷歌浏览器中出现乱码
fileName4 = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20").
* 根据操作人的名字和要验证码人的名字来生成注册码
*
* @param customName
* @param request
* @return
*/
@RequestMapping(value = "proRegisterCode", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg proRegisterCode(@RequestParam String customName, HttpServletRequest request) {
String registerCode = PassWordCreate.createPassWord(6);
VerifyCode verifyCode = new VerifyCode();
verifyCode.setState(false);
verifyCode.setRegisterCode(registerCode);
verifyCode.setOperatePerson(WebUtil.getUserNameByRequest(request));
verifyCode.setDate(new Date());
verifyCode.setCustomName(customName);
boolean result = iVerifyCodeService.save(verifyCode);
ResponseMsg responseMsg = new ResponseMsg();
responseMsg.setSuccess(result);
if (result) {
responseMsg.setMsg(registerCode);
} else {
responseMsg.setMsg("生成注册码失败,请重新操作!");
}
return responseMsg;
}
}
/**
* 拦截配置
*
*
*/
if (!link.isEmpty()) {
// downloadLink= fileService.fileShareCodeDecode(link);
downloadLink = link;
}
//在数据库查找这个链接
logger.warn("zc1+downloadLink:" + downloadLink);
LinkSecret linkSecret = linkSecretService.findLinkSecretBysecretLink(downloadLink);
if (linkSecret == null) {
ModelAndView modelAndView = new ModelAndView("errorPage");
modelAndView.addObject("message", "链接失效");
return modelAndView;
} else {
Date date1 = linkSecret.getExpireDate();
//表示链接永久有效
if (date1 == null) {
ModelAndView modelAndView = new ModelAndView("shareSecret");
modelAndView.addObject("link", link);
return modelAndView;
} else {
//得到long类型当前时间
long dataTemp = System.currentTimeMillis();
Date date2 = new Date(dataTemp);
if (date1.before(date2)) {
//不能下载
ModelAndView modelAndView = new ModelAndView("errorPage");
modelAndView.addObject("message", link + "链接失效");
//删除本地共享文件夹的内容
FileUtil.delete(downloadLink);
return modelAndView;
} else {
ModelAndView modelAndView = new ModelAndView("shareSecret");
modelAndView.addObject("link", link);
return modelAndView;
}
}
}
}
//定位到分享页面
@RequestMapping("/share")
public ModelAndView share(String link, HttpServletRequest request) {
logger.warn("zzc:" + link);
EncryptUtil des = null;
String linkDecoder = "";
try {
des = new EncryptUtil(key, "utf-8");
linkDecoder = des.decode(link);
} catch (Exception e) {
logger.error("Exception:", e);
}
ModelAndView modelAndView = new ModelAndView("share");
modelAndView.addObject("link", link);
modelAndView.addObject("linkDecoder", linkDecoder);
User user = (User) request.getSession().getAttribute("user");
if (user != null) {
modelAndView.addObject("author", user.getUserName());
}
return modelAndView;
}
@RequestMapping("/errorPage")
public ModelAndView errorPage(String message) {
logger.warn("zzc:" + message);
ModelAndView modelAndView = new ModelAndView("errorPage");
modelAndView.addObject("message", message);
return modelAndView;
}
@RequestMapping(value = "/sharefileSecret", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg shareFileSecret(String link, String secret, HttpServletRequest request,
HttpServletResponse response) {
logger.warn("执行sharefileSecret接口");
String downloadLink = "";
Map<Object, String> map = new HashMap<>();
if (!link.isEmpty()) {
// downloadLink= fileService.fileShareCodeDecode(link);
downloadLink = link;
}
//在数据库查找这个链接
LinkSecret linkSecret = linkSecretService.findLinkSecretBysecretLink(downloadLink);
String secret1 = linkSecret.getSecret();
//更新当前用户信息
@RequestMapping(value = "/updateUserByUserName")
@ResponseBody
public ResponseMsg updateUserByUserName(@RequestParam(required = false) String username,
@RequestParam(required = false) String alias, @RequestParam(required = false) String password,
@RequestParam(required = false) String email, @RequestParam(required = false) String phone,
HttpServletRequest request) {
ResponseMsg j = new ResponseMsg();
User user = (User) request.getSession().getAttribute("user");
if (username != null) {
user.setUserName(username);
}
if (alias != null) {
user.setAlias(alias);
}
if (password != null) {
try {
String encryptedPwd = Md5SaltTool.getEncryptedPwd(password);
user.setPassWord(encryptedPwd);
} catch (NoSuchAlgorithmException e) {
logger.error("NoSuchAlgorithmException:", e);
} catch (UnsupportedEncodingException e) {
logger.error("UnsupportedEncodingException:", e);
}
}
if (email != null) {
user.setEmail(email);
}
if (phone != null) {
user.setPhone(phone);
}
userService.update(user);
j.setMsg("更新用户信息成功!");
j.setSuccess(true);
return j;
}
//检查是否是登录状态
@RequestMapping(value = "/islogin")
@ResponseBody
public ResponseMsg isLogin(@RequestParam(required = false) String savePath, HttpServletRequest request) {
if (savePath == null) {
savePath = "/";
}
ResponseMsg j = new ResponseMsg();
logger.info("用户已经存在,请登录或换一个用户名!");
map.put("result", "0");
}
return map;
}
}
@RequestMapping(value = "/username", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg fileRename(HttpServletRequest request) {
ResponseMsg j = new ResponseMsg();
// 获取用户名
User user = (User) request.getSession().getAttribute("user");
String userName = user.getUserName();
if (userName == null) {
userName = "null";
}
j.setMsg(userName);
j.setSuccess(true);
return j;
}
@RequestMapping(value = "/getUserByUserName")
@ResponseBody
public User getUserByUserName(HttpServletRequest request) {
User user = (User) request.getSession().getAttribute("user");
return user;
}
//更新当前用户信息
@RequestMapping(value = "/updateUserByUserName")
@ResponseBody
public ResponseMsg updateUserByUserName(@RequestParam(required = false) String username,
@RequestParam(required = false) String alias, @RequestParam(required = false) String password,
@RequestParam(required = false) String email, @RequestParam(required = false) String phone,
HttpServletRequest request) {
ResponseMsg j = new ResponseMsg();
User user = (User) request.getSession().getAttribute("user");
if (username != null) {
user.setUserName(username);
}
if (alias != null) {
user.setAlias(alias);
}
if (password != null) {
try {
String encryptedPwd = Md5SaltTool.getEncryptedPwd(password);
user.setPassWord(encryptedPwd);
} catch (NoSuchAlgorithmException e) {
logger.error("NoSuchAlgorithmException:", e);
} catch (UnsupportedEncodingException e) {
logger.error("UnsupportedEncodingException:", e);
}
j.setMsg("更新用户信息成功!");
j.setSuccess(true);
return j;
}
//检查是否是登录状态
@RequestMapping(value = "/islogin")
@ResponseBody
public ResponseMsg isLogin(@RequestParam(required = false) String savePath, HttpServletRequest request) {
if (savePath == null) {
savePath = "/";
}
ResponseMsg j = new ResponseMsg();
// 获取用户名
User user = (User) request.getSession().getAttribute("user");
if (user == null) {
//未登录,跳转到登录界面,登录之后默认保存到网盘连接的地址<a href="wut://pan">链接到app</a>
j.setMsg("未登录");
j.setSuccess(false);
} else {
j.setMsg("已登录");
j.setSuccess(true);
}
return j;
}
}
//保存到网盘-----link是加密的链接 downloadLink解密后的链接/data/share/zc2/Fuck.java, path:保存路径--是用户名后面的路径
@RequestMapping(value = "/shareToMyPan")
@ResponseBody
public ResponseMsg shareToMyPan(HttpServletRequest request, String path, String link) {
String downloadLink = "";
if (link.contains("/data/share")) {
downloadLink = link;
} else {
downloadLink = fileService.fileShareCodeDecode(link);
}
logger.warn("downloadLink:" + downloadLink);
boolean b = false;
ResponseMsg responseMsg = new ResponseMsg();
User user = (User) request.getSession().getAttribute("user");
if (user == null) {
responseMsg.setSuccess(false);
responseMsg.setMsg("未登录");
} else {
String userName = user.getUserName();
if (path == null) {
path = "/";
}
logger.warn(userName + " " + downloadLink + " " + path);
b = fileService.copyFileToMyPan(userName, downloadLink, path);
responseMsg.setSuccess(b);
if (b == false) {
responseMsg.setMsg("保存失败");
} else {
responseMsg.setMsg("保存成功");
}
}
return responseMsg;
}
/**
* 下载客户端的apk
* filename:下载apk的名字
* downloadPath:下载的文件夹,放在/root/pan/share目录中
*/
@RequestMapping(value = "/downloadApk", produces = {"application/json; charset=UTF-8"})
@ResponseBody
public ResponseMsg shareToMyPan(HttpServletRequest request, HttpServletResponse response, String filename,
String downloadPath) throws FileNotFoundException, UnsupportedEncodingException {
// 读到流中
// String filePath="F:/"+downloadPath+"/"+filename;//window上测试的路径
ResponseMsg responseMsg = new ResponseMsg();
String filePath = fileRootPath + downloadPath + "/" + filename;
*/
@RequestMapping(value = "/downloadApk", produces = {"application/json; charset=UTF-8"})
@ResponseBody
public ResponseMsg shareToMyPan(HttpServletRequest request, HttpServletResponse response, String filename,
String downloadPath) throws FileNotFoundException, UnsupportedEncodingException {
// 读到流中
// String filePath="F:/"+downloadPath+"/"+filename;//window上测试的路径
ResponseMsg responseMsg = new ResponseMsg();
String filePath = fileRootPath + downloadPath + "/" + filename;
InputStream inStream = new FileInputStream(filePath);
if (!new File(filePath).exists()) {
responseMsg.setMsg("找不到文件");
}
// 设置输出的格式
String agent = request.getHeader("user-agent");
String fileName4 = "";
if (agent.contains("Firefox")) {
fileName4 = new String(filename.getBytes(), "iso-8859-1");
} else {
//空格,(,),;,@,#,&,逗号在谷歌浏览器中出现乱码
fileName4 = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20").
replaceAll("%28", "\\(").
replaceAll("%29", "\\)").
replaceAll("%3B", ";").
replaceAll("%40", "@").
replaceAll("%23", "\\#").
replaceAll("%26", "\\&").
replaceAll("%2C", "\\,");
}
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName4 + "\"");
// 循环取出流中的数据
byte[] b = new byte[100];
int len;
try {
while ((len = inStream.read(b)) > 0) {
response.getOutputStream().write(b, 0, len);
}
inStream.close();
responseMsg.setSuccess(true);
} catch (IOException e) {
logger.error("Exception:", e);
responseMsg.setSuccess(false);
}
return responseMsg;
HttpServletRequest request) {
ResponseMsg j = new ResponseMsg();
User user = (User) request.getSession().getAttribute("user");
if (username != null) {
user.setUserName(username);
}
if (alias != null) {
user.setAlias(alias);
}
if (password != null) {
try {
String encryptedPwd = Md5SaltTool.getEncryptedPwd(password);
user.setPassWord(encryptedPwd);
} catch (NoSuchAlgorithmException e) {
logger.error("NoSuchAlgorithmException:", e);
} catch (UnsupportedEncodingException e) {
logger.error("UnsupportedEncodingException:", e);
}
}
if (email != null) {
user.setEmail(email);
}
if (phone != null) {
user.setPhone(phone);
}
userService.update(user);
j.setMsg("更新用户信息成功!");
j.setSuccess(true);
return j;
}
//检查是否是登录状态
@RequestMapping(value = "/islogin")
@ResponseBody
public ResponseMsg isLogin(@RequestParam(required = false) String savePath, HttpServletRequest request) {
if (savePath == null) {
savePath = "/";
}
ResponseMsg j = new ResponseMsg();
// 获取用户名
User user = (User) request.getSession().getAttribute("user");
if (user == null) {
//未登录,跳转到登录界面,登录之后默认保存到网盘连接的地址<a href="wut://pan">链接到app</a>
j.setMsg("未登录");
j.setSuccess(false);
} else {
j.setMsg("已登录");
j.setSuccess(true);
}
return j;
}
}
}
}
//定位到分享页面
@RequestMapping("/share")
public ModelAndView share(String link, HttpServletRequest request) {
logger.warn("zzc:" + link);
EncryptUtil des = null;
String linkDecoder = "";
try {
des = new EncryptUtil(key, "utf-8");
linkDecoder = des.decode(link);
} catch (Exception e) {
logger.error("Exception:", e);
}
ModelAndView modelAndView = new ModelAndView("share");
modelAndView.addObject("link", link);
modelAndView.addObject("linkDecoder", linkDecoder);
User user = (User) request.getSession().getAttribute("user");
if (user != null) {
modelAndView.addObject("author", user.getUserName());
}
return modelAndView;
}
@RequestMapping("/errorPage")
public ModelAndView errorPage(String message) {
logger.warn("zzc:" + message);
ModelAndView modelAndView = new ModelAndView("errorPage");
modelAndView.addObject("message", message);
return modelAndView;
}
@RequestMapping(value = "/sharefileSecret", produces = "application/json; charset=utf-8")
@ResponseBody
File dir = new File(tempDir);
if (!dir.exists()) {
dir.mkdirs();
}
// 创建分片文件并保存
File chunkFile = new File(tempDir + "/" + chunk);
logger.warn(tempDir + "/" + chunk);
try {
chunkFile.createNewFile();
item.transferTo(chunkFile);
} catch (IllegalStateException e) {
logger.warn("保存分片文件出错:" + e.getMessage());
logger.error("Exception:", e);
} catch (IOException e) {
logger.warn("保存分片文件出错:" + e.getMessage());
logger.error("Exception:", e);
}
}
}
}
/**
* 上传之前检查
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/check", method = RequestMethod.POST)
@ResponseBody
public ResponseMsg checkChunk(HttpServletRequest request, HttpServletResponse response) {
ResponseMsg responseMsg = new ResponseMsg();
logger.warn("执行check-------------------");
String fileName = request.getParameter("fileName");
// String fileMd5 = request.getParameter("fileMd5");
String chunk = request.getParameter("chunk");
logger.warn("checkChunk+chunk:" + chunk);
String chunkSize = request.getParameter("chunkSize");
logger.warn("checkChunk+chunkSize:" + chunkSize);
String userName = WebUtil.getUserNameByRequest(request);
logger.warn(tempPath);
String tempDir = FileUtil.getTempDir(tempPath, userName, fileName);
tempDir = StringUtil.stringSlashToOne(tempDir);
File chunkFile = new File(tempDir + "/" + chunk);
boolean result = false;
// 分片文件是否存在,尺寸是否一致
if (chunkFile.exists() && chunkFile.length() == Integer.parseInt(chunkSize)) {
responseMsg.setSuccess(true);
responseMsg.setMsg(chunk);
}
return responseMsg;
}
return modelAndView;
} else {
ModelAndView modelAndView = new ModelAndView("shareSecret");
modelAndView.addObject("link", link);
return modelAndView;
}
}
}
}
//定位到分享页面
@RequestMapping("/share")
public ModelAndView share(String link, HttpServletRequest request) {
logger.warn("zzc:" + link);
EncryptUtil des = null;
String linkDecoder = "";
try {
des = new EncryptUtil(key, "utf-8");
linkDecoder = des.decode(link);
} catch (Exception e) {
logger.error("Exception:", e);
}
ModelAndView modelAndView = new ModelAndView("share");
modelAndView.addObject("link", link);
modelAndView.addObject("linkDecoder", linkDecoder);
User user = (User) request.getSession().getAttribute("user");
if (user != null) {
modelAndView.addObject("author", user.getUserName());
}
return modelAndView;
}
@RequestMapping("/errorPage")
public ModelAndView errorPage(String message) {
logger.warn("zzc:" + message);
ModelAndView modelAndView = new ModelAndView("errorPage");
modelAndView.addObject("message", message);
return modelAndView;
}
@RequestMapping(value = "/sharefileSecret", produces = "application/json; charset=utf-8")
@ResponseBody
public ResponseMsg shareFileSecret(String link, String secret, HttpServletRequest request,
HttpServletResponse response) {
logger.warn("执行sharefileSecret接口");
String downloadLink = "";
Map<Object, String> map = new HashMap<>();
if (!link.isEmpty()) {
// downloadLink= fileService.fileShareCodeDecode(link);
File f = new File(fullPath, FileUtil.getFileNameByContentDisposition(part.getHeader("content-disposition")));
if (!FileUtil.writeInputStreamToFile(part.getInputStream(), f)) {
throw new Exception("文件上传失败");
}
}
}
return new ResponseMsg("upload successful!");
} catch (Exception e) {
return new ResponseMsg();
}
}
/**
* 空间占用展示
*
* @param request HttpServletRequest
*/
@GetMapping(value = "/space")
public ResponseMsg getSpaceSize(HttpServletRequest request) {
// 普通用户限制80G,guest用户限制40G,
String userName = WebUtil.getUserNameByRequest(request);
Map<String, String> spaceMap = new HashMap<>(2);
spaceMap.put("totalSpace", "80");
double totalSpace = 80;
if ("guest".equals(userName)) {
spaceMap.put("totalSpace", "40");
totalSpace = 40;
}
long dirlength = SystemUtil.getDirSpaceSize(root + userName);
double dirlengthDouble = dirlength / 1024.0 / 1024 / 1024;
String usedeSpace = String.format("%.2f", dirlengthDouble);
String freeSpace = String.format("%.2f", totalSpace - Double.parseDouble(usedeSpace));
spaceMap.put("freeSpace", freeSpace);
return new ResponseMsg(JSONObject.toJSONString(spaceMap));
}
/**
* 用户文件列表展示
*
* @param path 路径
* @param request HttpServletRequest
* @return List<FileMsg>
*/
@RequestMapping(value = "/list", produces = "application/json; charset=utf-8")