【SSM + VUE网盘后端搭建】
SSM + VUE网盘后端搭建
一、数据库创建
-- MySQL dump 10.13 Distrib 5.5.53, for Win32 (AMD64)
--
-- Host: localhost Database: webpan
-- ------------------------------------------------------
-- Server version 5.5.53
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `apply`
--
DROP TABLE IF EXISTS `apply`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `apply` (
`applyId` int(255) NOT NULL AUTO_INCREMENT,
`applySize` double(11,2) DEFAULT NULL,
`applyStatus` varchar(30) DEFAULT NULL,
`applyRequestId` int(255) DEFAULT NULL,
PRIMARY KEY (`applyId`)
) ENGINE=MyISAM AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `apply`
--
LOCK TABLES `apply` WRITE;
/*!40000 ALTER TABLE `apply` DISABLE KEYS */;
INSERT INTO `apply` VALUES (26,500.00,'1',25);
/*!40000 ALTER TABLE `apply` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `file`
--
DROP TABLE IF EXISTS `file`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `file` (
`fileId` int(255) NOT NULL AUTO_INCREMENT,
`fileName` varchar(200) DEFAULT NULL,
`fileType` varchar(20) DEFAULT NULL,
`fileSize` double(10,2) DEFAULT NULL,
`fileUploadTime` datetime DEFAULT NULL,
`fileOwner` int(10) DEFAULT NULL,
`fileHash` varchar(100) DEFAULT NULL,
`filePath` varchar(200) DEFAULT NULL,
`fileGroup` int(20) NOT NULL DEFAULT '-1',
PRIMARY KEY (`fileId`)
) ENGINE=MyISAM AUTO_INCREMENT=178 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `file`
--
LOCK TABLES `file` WRITE;
/*!40000 ALTER TABLE `file` DISABLE KEYS */;
INSERT INTO `file` VALUES (175,'2021v3','pdf',0.40,'2021-09-11 14:12:33',25,'dc987d8371b1ee6b3a5e49a89cad9628','C:\\Users\\darkerg\\Desktop\\savefile\\xmr\\9792813\\2021v3.pdf',9792813),(176,'2021v3','pdf',0.40,'2021-09-11 15:14:08',41,'dc987d8371b1ee6b3a5e49a89cad9628','C:\\Users\\darkerg\\Desktop\\savefile\\lcx\\6104830\\2021v3.pdf',6104830),(177,'test1','txt',0.00,'2021-09-11 15:14:21',41,'1e28d14ab7c9de7e4af98e1db116c051','C:\\Users\\darkerg\\Desktop\\savefile\\lcx\\6104830\\test1.txt',6104830);
/*!40000 ALTER TABLE `file` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `groupinfo`
--
DROP TABLE IF EXISTS `groupinfo`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `groupinfo` (
`groupId` int(255) NOT NULL AUTO_INCREMENT,
`groupManagerId` int(255) DEFAULT NULL,
`groupUsage` double(11,2) DEFAULT '0.00',
`groupStorage` double(11,2) DEFAULT '10.00',
PRIMARY KEY (`groupId`)
) ENGINE=MyISAM AUTO_INCREMENT=9795206 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `groupinfo`
--
LOCK TABLES `groupinfo` WRITE;
/*!40000 ALTER TABLE `groupinfo` DISABLE KEYS */;
INSERT INTO `groupinfo` VALUES (4171877,25,0.00,20.00),(6104830,41,0.40,20.00),(9792813,25,0.40,20.00);
/*!40000 ALTER TABLE `groupinfo` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `user`
--
DROP TABLE IF EXISTS `user`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user` (
`userId` int(255) NOT NULL AUTO_INCREMENT,
`userName` varchar(30) DEFAULT NULL,
`userPassword` varchar(50) DEFAULT NULL,
`userUsage` double(11,2) DEFAULT '0.00',
`userStorage` double(11,2) DEFAULT '10.00',
`userKey` varchar(100) DEFAULT NULL,
`userEmail` varchar(30) DEFAULT NULL,
`userType` varchar(11) DEFAULT 'user',
`userStatus` tinyint(1) DEFAULT '0',
PRIMARY KEY (`userId`)
) ENGINE=MyISAM AUTO_INCREMENT=42 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `user`
--
LOCK TABLES `user` WRITE;
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` VALUES (25,'xmr','66be31688e0bc5d503c4a271675e08c3e13183c40260ba0c',0.00,500.00,'d111be4cd85afd6d345ebe819a3339c5','894785927@qq.com','admin',1),(41,'lcx','74744ae9d369861220c34e11a1577fe7a421994e62c4925c',0.00,10.00,'152efec44c936b44535682ac891cf0ce','479502327@qq.com','user',0);
/*!40000 ALTER TABLE `user` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `usergroupfile`
--
DROP TABLE IF EXISTS `usergroupfile`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `usergroupfile` (
`usergroupfile` int(255) NOT NULL AUTO_INCREMENT,
`userId` int(255) DEFAULT NULL,
`groupId` int(255) DEFAULT NULL,
`fileId` int(255) DEFAULT NULL,
PRIMARY KEY (`usergroupfile`)
) ENGINE=MyISAM AUTO_INCREMENT=76 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `usergroupfile`
--
LOCK TABLES `usergroupfile` WRITE;
/*!40000 ALTER TABLE `usergroupfile` DISABLE KEYS */;
INSERT INTO `usergroupfile` VALUES (74,41,6104830,NULL),(72,25,9792813,NULL),(73,25,4171877,NULL),(75,25,6104830,NULL);
/*!40000 ALTER TABLE `usergroupfile` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2021-09-15 23:27:27
二、创建基本的项目结构
不要忘记添加web依赖
1、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>org.example</groupId>
<artifactId>vueyunpan</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<!--依赖:junit,数据库驱动,连接池,servlet,jsp,mybatis,mybatis-spring,spring-->
<dependencies>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--数据库连接池:c3p0:dbcp-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!--Servlet-JSP-->
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/taglibs/standard -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency><!--Spring操作数据库,还需要一个spring-jdbc-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
<dependency>
<groupId>org.apache.directory.studio</groupId>
<artifactId>org.apache.commons.codec</artifactId>
<version>1.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.activation/activation -->
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<!--token生成-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.3.0</version>
</dependency>
</dependencies>
<!--静态资源导出问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
2、pojo实体类
User.java
package com.bupt.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
private int userId;
private String userName;
private String userPassword;
private double userUsage;
private double userStorage;
private String userKey;
private String userEmail;
private String userType;
private boolean userStatus;
}
File.java
package com.bupt.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class File {
private int fileId;
private String fileName;
private String fileType;
private double fileSize;
private Date fileTime;
private int fileOwner;
private String fileHash;
private String filePath;
private int fileGroup;
}
Apply.java
package com.bupt.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Apply {
private int applyId;
private double applySize;
private String applyStatus;
private int applyRequestId;
}
Group.java
package com.bupt.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Group {
private int groupId;
private int groupManagerId;
private double groupUsage;
private double groupStorage;
}
Code.java
package com.bupt.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Code {
private String sjs;
}
3、Dao层
①UserMapper接口
package com.bupt.dao;
import com.bupt.pojo.File;
import com.bupt.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserMapper {
int register(@Param("userName")String userName,@Param("userEmail")String userEmail,@Param("userPassword")String userPassword,@Param("userKey")String userKey);
User login(@Param("User")String user,@Param("userPassword")String userPassword);
User queryUserById(@Param("userId") int userId);
User queryUserByName(@Param("userName")String userName);
User queryUserByEmail(@Param("userEmail")String userEmail);
int checkName(@Param("userName")String userName);
int checkEmail(@Param("userEmail")String userEmail);
int applyApply(@Param("applySize") double applySize,@Param("applyRequestId") int applyRequestId);
int applyUser(@Param("userName") String userName);
List<File> getFileById(@Param("userId")int userId);
int changePwd(@Param("userEmail")String userEmail,@Param("userPassword")String userPassword);
}
UserMapper.xml
<?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">
<!--namespace=绑定一个对应的Dao/mapper接口-->
<mapper namespace="com.bupt.dao.UserMapper">
<insert id="register" parameterType="java.lang.String">
insert into webpan.user(userName,userPassword,userUsage,userStorage,userKey,userEmail,userType,userStatus)
value
(#{userName},#{userPassword},0.0,10.0,#{userKey},#{userEmail},'user',0)
</insert>
<select id="login" parameterType="java.lang.String" resultType="User">
select distinct *
from webpan.user
where userName = #{User} and userPassword = #{userPassword}
or userEmail = #{User} and userPassword = #{userPassword}
or userId = #{User} and userPassword = #{userPassword}
</select>
<!-- //绑定对应的接口id是接口中的哪个方法,参数类型,结果类型 加上数据库名 前面的是数据库的属性名,后面取出来前面方法传进来param里面的-->
<select id="queryUserById" parameterType="int" resultType="User">
select *
from webpan.user
where userId=#{userId}
</select>
<select id="queryUserByName" parameterType="String" resultType="User">
select *
from webpan.user
where userName=#{userName}
</select>
<select id="queryUserByEmail" parameterType="String" resultType="User">
select *
from webpan.user
where userEmail=#{userEmail}
</select>
<select id="checkName" resultType="java.lang.Integer" parameterType="java.lang.String">
select count(*)
from webpan.user
where userName = #{userName}
</select>
<select id="checkEmail" resultType="java.lang.Integer" parameterType="java.lang.String">
select count(*)
from webpan.user
where userEmail = #{userEmail}
</select>
<insert id="applyApply">
insert into webpan.Apply (applySize,applyStatus,applyRequestId)
value
(#{applySize},1,#{applyRequestId})
</insert>
<update id="applyUser">
update webpan.user
set userStatus = 1
where userName = #{userName}
</update>
<select id="getFileById" resultType="File">
select *
from webpan.file
where fileOwner = #{userId} and fileGroup = -1
</select>
<update id="changePwd">
update webpan.user
set userPassword=#{userPassword}
where userEmail=#{userEmail}
</update>
</mapper>
②FileMapper接口
FileMapper
package com.bupt.dao;
import com.bupt.pojo.File;
import com.bupt.pojo.User;
import org.apache.ibatis.annotations.Param;
public interface FileMapper {
//修改存储量
int InsertFileInfo(@Param("name")String name, @Param("type")String type, @Param("size")double size,
@Param("time")String time, @Param("owner")int owner, @Param("hash")String hash, @Param("path")String path);
int AddStorage(@Param("owner")int owner, @Param("size")double size);
int SubStorage(@Param("ownerId")int owner, @Param("size")double size);
int DeleteFile(@Param("file_id")int file_id);
File GetFileById(@Param("file_id")int fileId);
File GetFileByName(@Param("file_name")String fileName,@Param("file_type")String fileType,@Param("owner_id")int ownerId);
User GetOwnerByFile(@Param("file_id")int fileId);
int ChangeFileName(@Param("file_id")int fileId, @Param("file_name")String new_filename, @Param("file_path")String new_filepath);
File GetGroupFileById(@Param("file_id")int fileId,@Param("group_id")int groupId);
}
FileMapper.xml
<?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">
<!--namespace=绑定一个对应的Dao/mapper接口-->
<mapper namespace="com.bupt.dao.FileMapper">
<insert id="InsertFileInfo">
insert into file (fileName,fileType,fileSize,fileUploadTime,fileOwner,fileHash,filePath)
value
(#{name},#{type},#{size},#{time},#{owner},#{hash},#{path})
</insert>
<update id="AddStorage">
update webpan.user
set userUsage = userUsage + #{size}
where userId = #{owner}
</update>
<update id="SubStorage">
update webpan.user
set userUsage = userUsage - #{size}
where userId = #{ownerId}
</update>
<delete id="DeleteFile">
delete
from file
where fileId = #{file_id} and fileGroup = -1
</delete>
<select id="GetFileById" resultType="File">
select distinct *
from file
where fileId = #{file_id} and fileGroup = -1
</select>
<select id="GetGroupFileById" resultType="File">
select distinct *
from file
where fileId = #{file_id} and fileGroup = #{group_id}
</select>
<select id="GetFileByName" resultType="File" >
select distinct * from webpan.file
where fileName = #{file_name} and fileOwner = #{owner_id} and fileType = #{file_type} and fileGroup = -1
</select>
<select id="GetOwnerByFile" resultType="User">
select distinct *
from user
where userId = (select fileOwner from file where fileId=#{file_id})
</select>
<update id="ChangeFileName">
update file
set fileName = #{file_name}, filePath = #{file_path}
where fileId = #{file_id} fileGroup = -1
</update>
</mapper>
③GroupMapper接口
package com.bupt.dao;
import com.bupt.pojo.File;
import com.bupt.pojo.Group;
import com.bupt.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface GroupMapper {
int registerGroup(@Param("userId") int userId,@Param("groupId") int groupId);
int addGroup(@Param("userId") int userId,@Param("groupId") int groupId);
Group getGroupById(@Param("groupId") int groupId);
List<Group> getGroups(@Param("userId") int userId);
List<Group> getGroupsManage(@Param("userId")int userId);
Group getGroupInfoById(@Param("groupId") int groupId);
int InsertFileInfo(@Param("name")String name, @Param("type")String type, @Param("size")double size,
@Param("time")String time, @Param("owner")int owner, @Param("group")int group, @Param("hash")String hash, @Param("path")String path);
// int judgeGroupById(@Param("userId") int userId,@Param("groupId") int groupId);
// int addUserGroupFile(@Param("userId")int userId, @Param("groupId")int groupId, @Param("fileId")int fileId);
File GetFileById(@Param("fileName")String fileName,@Param("fileType") String fileType,@Param("groupId")int groupId,@Param("userId")int userId);
File GetFileById2(@Param("fileName")String fileName,@Param("fileType") String fileType,@Param("groupId")int groupId);
User getUserByGroupFile(@Param("groupId") int groupId,@Param("fileId") int fileId);
List<File> GetFileByGroup(@Param("groupId") int groupId);
int getGroupNumById(@Param("groupId") int groupId);
int SubStorage(@Param("groupId") int groupId,@Param("size") double size);
int DeleteFile(@Param("file_id")int file_id);
int AddStorage(@Param("groupId") int groupId,@Param("size") double size);
}
GroupMapper.xml
<?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">
<!--namespace=绑定一个对应的Dao/mapper接口-->
<mapper namespace="com.bupt.dao.GroupMapper">
<insert id="registerGroup">
insert into webpan.groupinfo(groupId,groupManagerId, groupUsage, groupStorage)
value(#{groupId},#{userId},0.0,20.0)
</insert>
<insert id="addGroup">
insert into webpan.usergroupfile(userId, groupId)
value(#{userId},#{groupId})
</insert>
<select id="getGroupById" resultType="Group">
select *
from webpan.groupinfo
where groupId = #{groupId}
</select>
<select id="getGroupNumById" resultType="int">
select COUNT(*)
from webpan.groupinfo
where groupId = #{groupId}
</select>
<select id="getGroups" resultType="Group" parameterType="int">
select *
from webpan.groupinfo
where groupId in (
select distinct groupId
from webpan.usergroupfile
where userId = #{userId}
)
</select>
<select id="getGroupsManage" resultType="Group" parameterType="int">
select *
from webpan.groupinfo
where groupManagerId = #{userId}
</select>
<select id="getGroupInfoById" resultType="Group">
select *
from webpan.groupinfo
where groupId=#{groupId}
</select>
<insert id="InsertFileInfo">
insert into file (fileName,fileType,fileSize,fileUploadTime,fileOwner,fileGroup,fileHash,filePath)
value
(#{name},#{type},#{size},#{time},#{owner},#{group},#{hash},#{path})
</insert>
<select id="GetFileByGroup" resultType="file">
select *
from file
where fileGroup=#{groupId}
</select>
<select id="GetFileById" resultType="File" >
select distinct * from webpan.file
where fileName = #{fileName} and fileType = #{fileType} and fileOwner = #{userId} and fileGroup = #{groupId}
</select>
<select id="GetFileById2" resultType="File" >
select distinct * from webpan.file
where fileName = #{fileName} and fileType = #{fileType} and fileGroup = #{groupId}
</select>
<select id="getUserByGroupFile" resultType="User">
select *from user
where userId= (
select fileOwner
from webpan.file
where fileId = #{fileId}
and fileGroup =#{groupId}
)
</select>
<update id="AddStorage">
update webpan.groupinfo
set groupUsage = groupUsage + #{size}
where groupId = #{groupId}
</update>
<update id="SubStorage">
update webpan.groupinfo
set groupUsage = groupUsage - #{size}
where groupId = #{groupId}
</update>
<delete id="DeleteFile">
delete
from file
where fileId = #{file_id}
</delete>
</mapper>
④ManagerMapper
package com.bupt.dao;
import com.bupt.pojo.Apply;
import com.bupt.pojo.Group;
import com.bupt.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ManagerMapper {
public List<User> getAllUsers();
public List<Group> getAllGroups();
public List<Apply> getAllApplies();
public List<User> getApplyUsers();
public int setUserStorage(@Param("userId")int ID, @Param("Size")double size);
public int setGroupStorage(@Param("groupId")int ID, @Param("Size")double size);
public User GetUserbyid(@Param("userId")int id);
public Group GetGroupbyid(@Param("groupId")int id);
public int refuseUserApply(@Param("userId")int userId);
public int refuseUser(@Param("userId")int userId);
public int agreeUserApply(@Param("userId")int userId,@Param("Size")double size);
public int agreeUser(@Param("userId")int userId,@Param("Size")double size);
public int DeleteApply(@Param("userId")int userId);
}
ManagerMapper.xml
<?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">
<!--namespace=绑定一个队形的Dao/mapper接口-->
<mapper namespace="com.bupt.dao.ManagerMapper">
<select id="getAllUsers" resultType="User">
select distinct *
from webpan.user
order by userId
</select>
<select id="getAllGroups" resultType="Group">
select distinct *
from webpan.groupinfo
order by groupId
</select>
<select id="getAllApplies" resultType="Apply">
select distinct *
from webpan.apply
order by applyId desc
</select>
<select id="getApplyUsers" resultType="User">
select userId,userName,userPassword,userUsage,userStorage,userKey,userEmail,userType
from webpan.user, webpan.apply
where userId = applyRequestId
</select>
<update id = "setUserStorage">
update webpan.user
set userStorage = #{Size}
where userId = #{userId}
</update>
<update id = "setGroupStorage">
update webpan.groupinfo
set groupStorage = #{Size}
where groupId = #{groupId}
</update>
<update id = "refuseUserApply">
update webpan.apply
set applyStatus = 0
where applyRequestId = #{userId}
</update>
<update id = "refuseUser">
update webpan.user
set userStatus = 0
where userId = #{userId}
</update>
<update id = "agreeUserApply">
update webpan.apply
set applyStatus = 0
where applyRequestId = #{userId}
</update>
<update id = "agreeUser">
update webpan.user
set userStatus = 0, userStorage = userStorage + #{Size}
where userId = #{userId}
</update>
<delete id="DeleteApply">
delete
from webpan.apply
where applyRequestId = #{userId}
</delete>
<select id="GetUserbyid" parameterType="int" resultType="User">
select distinct *
from webpan.user
where userId = #{userId}
</select>
<select id="GetGroupbyid" parameterType="int" resultType="Group">
select distinct *
from webpan.groupinfo
where groupId = #{groupId}
</select>
</mapper>
4、Service层
①UserService接口
package com.bupt.service;
import com.bupt.pojo.File;
import com.bupt.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.security.NoSuchAlgorithmException;
import java.util.List;
public interface UserService {
int register(String userName,String userEmail,String userPassword) throws NoSuchAlgorithmException;
User login(String user,String userPassword);
User queryUserById( int userId);
User queryUserByName(String userName);
User queryUserByEmail(String userEmail);
int checkName(String userName);
int checkEmail(String userEmail);
int apply(double applySize,int userId,String userName);
List<File> getFileById(int userId);
int changePwd(String userEmail,String userPassword) ;
}
UserServiceImpl
package com.bupt.service;
import com.bupt.dao.UserMapper;
import com.bupt.pojo.File;
import com.bupt.pojo.User;
import org.apache.commons.codec.binary.Hex;
import javax.annotation.Resource;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.List;
public class UserServiceImpl implements UserService{
@Resource
private UserMapper userMapper;
//私有属性userMapper初始化
public void setUserMapper(UserMapper userMapper){
this.userMapper = userMapper;
}
@Override
public int register(String name,String email,String pwd) throws NoSuchAlgorithmException{
System.out.println("进入了注册业务");
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
System.out.println("keyGen"+keyGen);
SecureRandom secRan = new SecureRandom();
System.out.println("secRan"+secRan);
keyGen.init(secRan);
SecretKey secretKey = keyGen.generateKey();
System.out.println("secretKey"+secretKey);
byte[] keyBytes = secretKey.getEncoded();
String key = Hex.encodeHexString(keyBytes);
System.out.println("key"+key);
int result = userMapper.register(name,email,pwd,key);
System.out.println(result);
if(result==0)
return 0;//失败
else
return 1;
}
public User login(String user,String userPassword){
return userMapper.login(user, userPassword);
}
public User queryUserById(int id) {
//userMapper已经定义了,直接用
//User user = userMapper.queryUserById(id)//alt+回车
//System.out.println(user.getUserName());在业务层随意增加代码
return userMapper.queryUserById(id);
}
public User queryUserByName(String name){
return userMapper.queryUserByName(name);
}
public User queryUserByEmail(String email){
return userMapper.queryUserByEmail(email);
}
public int checkName(String userName){
return userMapper.checkName(userName);
}
public int checkEmail(String userEmail){
return userMapper.checkEmail(userEmail);
}
public List<File> getFileById(int userId)
{
List<File> fileList = userMapper.getFileById(userId);
return fileList;
}
public int apply(double applySize,int userId,String userName) {
return userMapper.applyApply(applySize,userId)*userMapper.applyUser(userName);
}
public int changePwd(String userEmail,String userPassword) {
return userMapper.changePwd(userEmail,userPassword);
}
}
②FileService接口
package com.bupt.service;
import org.apache.ibatis.annotations.Param;
import com.bupt.pojo.File;
import com.bupt.pojo.User;
public interface FileService
{
public int InsertFileInfo(String name,String type,double size,String time,int owner,String hash,String path);
public int SubStorage(int owner,double size);
public int DeleteFile(int delete);
public int AddStorage(int owner,double size);
File GetFileById(int fileId);
File GetFileByName(String fileName,String fileType,int ownerId);
File GetGroupFileById(int fileId,int groupId);
User GetOwnerByFile(int fileId);
int ChangeFileName(int fileId,String new_filename,String new_filepath);
}
FileServiceImpl
package com.bupt.service;
import com.bupt.dao.FileMapper;
import com.bupt.pojo.File;
import com.bupt.pojo.User;
import javax.annotation.Resource;
public class FileServiceImpl implements FileService{
@Resource
public FileMapper fileMapper;
public void setFileMapper(FileMapper fileMapper){
this.fileMapper = fileMapper;
}
@Override
public int InsertFileInfo(String name, String type, double size, String time, int owner, String hash, String path) {
return fileMapper.InsertFileInfo(name, type, size, time, owner, hash, path);
}
@Override
public int AddStorage(int owner, double size) {
return fileMapper.AddStorage(owner, size);
}
@Override
public int SubStorage(int owner, double size) {
return fileMapper.SubStorage(owner, size);
}
public int DeleteFile(int file_id) {
return fileMapper.DeleteFile(file_id);
}
@Override
public File GetGroupFileById(int fileId, int groupId) {
return fileMapper.GetGroupFileById(fileId,groupId);
}
public File GetFileById(int fileId) {
return fileMapper.GetFileById(fileId);
}
public File GetFileByName(String fileName, String fileType, int ownerId){
return fileMapper.GetFileByName(fileName,fileType,ownerId);
}
public User GetOwnerByFile(int fileId){
return fileMapper.GetOwnerByFile(fileId);
}
public int ChangeFileName(int fileId,String new_filename,String new_filepath){
return fileMapper.ChangeFileName(fileId,new_filename,new_filepath);
}
}
③GroupService接口
package com.bupt.service;
import com.bupt.pojo.File;
import com.bupt.pojo.Group;
import com.bupt.pojo.User;
import org.apache.ibatis.annotations.Param;
import javax.jws.soap.SOAPBinding;
import java.util.List;
public interface GroupService {
//创建group,随机生成groupId
int registerGroup(int userId,int groupId);
//通过groupId添加
int addGroup(int userId,int groupId);
//通过groupId判断是否存在这一个group
Group getGroupById(int groupId);
int getGroupNumById(int groupId);
//将user所在的group都找出来
List<Group> getGroups(int userId);
//将user管理的group都找出来
List<Group> getGroupsManage(int userId);
// 通过groupId获取整个group
Group getGroupInfoById(int groupId);
//插入文件数据进入数据库
int InsertFileInfo(String name,String type,double size,String time,int owner,int group,String hash,String path);
User getUserByGroupFile(int groupId, int fileId);
//通过groupId判断user是否已经加入该群组
// int judgeGroupById(int userId, int groupId);
// int addUserGroupFile(int userId, int groupId, String filename ,String filetype);
//在GUF表中get文件
File GetFileById(String fileName, String fileType,int groupId,int userId);
//test
File GetFileById2(String fileName, String fileType, int groupId);
List<File> GetFileByGroup(int groupId);
int SubStorage(int groupId,double size);
int DeleteFile(int delete);
int AddStorage(int groupId,double size);
}
GroupServiceImpl
package com.bupt.service;
import com.bupt.dao.GroupMapper;
import com.bupt.dao.UserMapper;
import com.bupt.pojo.File;
import com.bupt.pojo.Group;
import com.bupt.pojo.User;
import org.apache.ibatis.annotations.Param;
import javax.annotation.Resource;
import java.util.List;
public class GroupServiceImpl implements GroupService{
@Resource
private GroupMapper groupMapper;
//私有属性groupMapper初始化
public void setGroupMapper(GroupMapper groupMapper) {
this.groupMapper = groupMapper;
}
public int registerGroup(int userId,int groupId){
return groupMapper.registerGroup(userId,groupId);
}
public int addGroup(int userId,int groupId){
return groupMapper.addGroup(userId,groupId);
}
//通过groupId判断是否存在这一个group
public Group getGroupById(int groupId){
return groupMapper.getGroupById(groupId);
}
public int getGroupNumById(int groupId){
return groupMapper.getGroupNumById(groupId);
}
//将user所在的group都找出来
public List<Group> getGroups(int userId){
return groupMapper.getGroups(userId);
}
//将user管理的group都找出来
public List<Group> getGroupsManage(int userId){
return groupMapper.getGroupsManage(userId);
}
public Group getGroupInfoById(int groupId) { return groupMapper.getGroupInfoById(groupId); }
public int InsertFileInfo(String name,String type,double size,String time,int owner,int group,String hash,String path){
return groupMapper.InsertFileInfo(name, type, size, time, owner, group, hash, path);
}
public int SubStorage(int groupId,double size){
return groupMapper.SubStorage(groupId,size);
}
public int DeleteFile(int file_id) {
return groupMapper.DeleteFile(file_id);
}
public int AddStorage(int groupId,double size){
return groupMapper.AddStorage(groupId,size);
}
//通过groupId判断user是否已经加入该群组
// public int judgeGroupById(int userId,int groupId){
// return groupMapper.judgeGroupById(userId,groupId);
// }
//
// public int addUserGroupFile(int userId, int groupId, int fileId){
// return groupMapper.addUserGroupFile(userId, groupId, fileId);
// }
public File GetFileById(String fileName, String fileType, int groupId, int userId){
return groupMapper.GetFileById(fileName,fileType, groupId, userId);
}
public User getUserByGroupFile(int groupId, int fileId){
return groupMapper.getUserByGroupFile(groupId, fileId);
}
public List<File> GetFileByGroup(int groupId){
return groupMapper.GetFileByGroup(groupId);
}
@Override
public File GetFileById2(String fileName, String fileType, int groupId) {
return groupMapper.GetFileById2(fileName,fileType,groupId);
}
}
④ManagerService
package com.bupt.service;
import com.bupt.pojo.Apply;
import com.bupt.pojo.Group;
import com.bupt.pojo.User;
import java.util.List;
public interface ManagerService {
//获取用户信息列表
public List<User> getAllUsers();
//获取群组信息列表
public List<Group> getAllGroups();
//获取申请列表
public List<Apply> getAllApplies();
public List<User> getApplyUsers();
//设置存储空间
public int SetUserStorage(int ID, double size);
public int SetGroupStorage(int ID, double size);
public User GetUserbyid(int id);
public Group GetGroupbyid(int id);
//同意请求
public int AgreeApply(int applyRequestId,double size);
//拒绝请求
public int RefuseApply(int applyRequestId);
//删除请求
public int DeleteApply(int applyRequestId);
}
ManagerServiceImpl
package com.bupt.service;
import com.bupt.dao.ManagerMapper;
import com.bupt.pojo.Apply;
import com.bupt.pojo.Group;
import com.bupt.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import javax.annotation.Resource;
import java.util.List;
public class ManagerServiceImpl implements ManagerService{
@Resource
private ManagerMapper managerMapper;
public void setManagerMapper(ManagerMapper managerMapper){
this.managerMapper = managerMapper;
}
@Override
public List<User> getAllUsers(){
return managerMapper.getAllUsers();
}
@Override
public List<Group> getAllGroups() {
return managerMapper.getAllGroups();
}
@Override
public List<Apply> getAllApplies() {
return managerMapper.getAllApplies();
}
@Override
public List<User> getApplyUsers() {
return managerMapper.getApplyUsers();
}
@Override
public int SetUserStorage(int ID, double size) {
return managerMapper.setUserStorage(ID,size);
}
@Override
public int SetGroupStorage(int ID, double size) {
return managerMapper.setGroupStorage(ID,size);
}
@Override
public User GetUserbyid(int id) {
return managerMapper.GetUserbyid(id);
}
@Override
public Group GetGroupbyid(int id) {
return managerMapper.GetGroupbyid(id);
}
@Override
public int AgreeApply(int applyRequestId, double size) {
return managerMapper.agreeUserApply(applyRequestId,size)*managerMapper.agreeUser(applyRequestId,size) ;
}
@Override
public int RefuseApply(int applyRequestId) {
return managerMapper.refuseUserApply(applyRequestId)*managerMapper.refuseUser(applyRequestId);
}
@Override
public int DeleteApply(int applyID) {
return managerMapper.DeleteApply(applyID);
}
}
5、tools用到的自定义加密文件处理
①EncryptAndDecrypt.java
package com.bupt.tools;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import org.apache.commons.codec.binary.Hex;
import org.springframework.web.multipart.MultipartFile;
public class EncryptAndDecrypt {
private final static String IV_PARAMETER = "12345678";
private static final String CIPHER_ALGORITHM = "DES";
private static final String CHARSET = "utf-8";
public static void DESEncrypt(MultipartFile src_file,String dst_file,String key) throws Exception
{
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
Key des_key = GetKey(key);
//String s = Hex.encodeHexString(des_key.getEncoded());
cipher.init(Cipher.ENCRYPT_MODE, des_key);
InputStream in = src_file.getInputStream();
OutputStream out = new FileOutputStream(dst_file);
CipherInputStream cis = new CipherInputStream(in, cipher);
byte[] buffer = new byte[1024];
int r;
while ((r = cis.read(buffer)) > 0) {
out.write(buffer, 0, r);
}
cis.close();
in.close();
out.close();
}
public static void DESDecrypt(File src_file, String dst_file, String key) throws Exception
{
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
Key des_key = GetKey(key);
cipher.init(Cipher.DECRYPT_MODE, des_key);
InputStream in = new FileInputStream(src_file);
OutputStream out = new FileOutputStream(dst_file);
CipherOutputStream cos = new CipherOutputStream(out, cipher);
byte[] buffer = new byte[1024];
int r;
while ((r = in.read(buffer)) >= 0) {
cos.write(buffer, 0, r);
}
cos.close();
in.close();
out.close();
}
public static void DESEncrypt(String src_file,String dst_file,String key) throws Exception
{
Cipher cipher = Cipher.getInstance("DES");
Key des_key = GetKey(key);
cipher.init(Cipher.ENCRYPT_MODE, des_key);
InputStream in = new FileInputStream(src_file);
OutputStream out = new FileOutputStream(dst_file);
CipherInputStream cis = new CipherInputStream(in, cipher);
byte[] buffer = new byte[1024];
int r;
while ((r = cis.read(buffer)) > 0) {
out.write(buffer, 0, r);
}
cis.close();
in.close();
out.close();
}
public static Key GetKey(String key) throws Exception
{
KeyGenerator kg = KeyGenerator.getInstance("DES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
secureRandom.setSeed(key.getBytes());
kg.init(secureRandom);
Key des_key=kg.generateKey();
return des_key;
}
public static String EncryptFileId(String src,String key)
{
char[] p = key.toCharArray(); // 字符串转字符数组
int n = p.length; // 密码长度
char[] c = src.toCharArray();
int m = c.length; // 字符串长度
for (int k = 0; k < m; k++) {
int mima = c[k] + p[k / n]; // 加密
c[k] = (char) mima;
}
return new String(c);
}
public static String DecryptFileId(String src,String key)
{
char[] p = key.toCharArray(); // 字符串转字符数组
int n = p.length; // 密码长度
char[] c = src.toCharArray();
int m = c.length; // 字符串长度
for (int k = 0; k < m; k++) {
int mima = c[k] - p[k / n]; // 解密
c[k] = (char) mima;
}
return new String(c);
}
}
②FiletoByte.java
package com.bupt.tools;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
public class FiletoByte
{
public static byte[] getBytesByFile(String pathStr) {
File file = new File(pathStr);
try {
FileInputStream fis = new FileInputStream(file);
System.out.println("fis="+fis);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
byte[] data = bos.toByteArray();
System.out.println("data="+data);
bos.close();
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
6、utils工具包
①JsonUtils.java--用于将对象转换为Json串
package com.bupt.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
public class JsonUtils {
public static String getJson(Object object){
return getJson(object,"yyyy-MM-dd HH:mm:ss");
}
public static String getJson(Object object,String dateFormat){
ObjectMapper mapper = new ObjectMapper();
//不实用时间戳的方式
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
//自定义日期的格式
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
②JwtUtil--用于JWT生成验证
package com.bupt.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JwtUtil {
/**
* 过期时间一天,
* TODO 正式运行时修改为15分钟
*/
private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;
/**
* token私钥
*/
// private static final String TOKEN_SECRET = "f26e587c28064d0e855e72c0a6a0e618";
private static final String TOKEN_SECRET = "vueyunpan";
/**
* 校验token是否正确
*
* @param token 密钥
* @return 是否正确
*/
public static boolean verify(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm)
.build();
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (Exception exception) {
return false;
}
}
/**
* 获得token中的信息无需secret解密也能获得
*
* @return token中包含的用户名
*/
public static String getUsername(String token) {
try {
DecodedJWT jwt = JWT.decode(token);
return jwt.getClaim("loginName").asString();
} catch (JWTDecodeException e) {
return null;
}
}
/**
* 获取登陆用户ID
* @param token
* @return
*/
public static String getUserId(String token) {
try {
DecodedJWT jwt = JWT.decode(token);
return jwt.getClaim("userId").asString();
} catch (JWTDecodeException e) {
return null;
}
}
/**
* 生成签名,15min后过期
*
* @param username 用户名
* @return 加密的token
*/
public static String sign(String username,String userId) {
try {
// 过期时间
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
// 私钥及加密算法
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
// 设置头部信息
Map<String, Object> header = new HashMap<>(2);
header.put("typ", "JWT");
header.put("alg", "HS256");
// 附带username,userId信息,生成签名
return JWT.create()
.withHeader(header)
.withClaim("loginName", username)
.withClaim("userId",userId)
.withExpiresAt(date)
.sign(algorithm);
} catch (UnsupportedEncodingException e) {
return null;
}
}
}
③Sendmail.java---用于发送验证码邮件
package com.bupt.utils;
import com.bupt.pojo.User;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
//网站3秒原则:用户体验
//多线程提高用户体验!(异步处理)
public class Sendmail extends Thread{
//用于给用户发送邮件的邮箱
private String from = "";
//邮箱的用户名
private String username = "";
//邮箱的授权码
private String password = "";
//发送邮件的服务器地址
private String host = "smtp.qq.com";
private User user;
private String sjs;
public Sendmail(User user,String sjs){
this.user = user;
this.sjs = sjs;
}
//重写run方法,在run方法中发送邮件给指定的用户
@Override
public void run() {
try{
Properties prop = new Properties();
prop.setProperty("mail.host",host);//设置QQ邮件服务器
prop.setProperty("mail.transport.protocol","smtp");//邮件发送协议
prop.setProperty("mail.smtp.auth","true");//需要验证用户名和密码
//关于QQ邮箱,还要设置SSL加密,加上以下代码即可,其他邮箱不需要
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable","true");
prop.put("mail.smtp.ssl.socketFactory",sf);
//使用JavaMail发送邮件的5个步骤
//1.创建定义整个应用程序所需的环境信息的Session对象
//QQ才有!其他邮箱就不用
Session session = Session.getDefaultInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,password);
}
});
session.setDebug(true);
//2.通过session得到transport对象
Transport ts = session.getTransport();
//3.使用邮箱的用户名和授权码连接上邮件服务器
ts.connect(host,username,password);
//4.创建邮件:写邮件
//注意需要传递session
MimeMessage message = new MimeMessage(session);
//指明邮件的发件人
message.setFrom(new InternetAddress(from));
//指明邮件的收件人,现在发件人和收件人是一样的,那就是给自己发
message.setRecipient(Message.RecipientType.TO,new InternetAddress(user.getUserEmail()));
//邮件的标题
message.setSubject("用户找回密码邮件");
//邮件的文本内容
String info = "您的验证码为:"+sjs;
message.setContent(info,"text/html;charset=UTF-8");
//5.发送邮件
ts.sendMessage(message,message.getAllRecipients());
//6.关闭连接
ts.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
7、Controller层
①UserController.java
package com.bupt.controller;
import com.bupt.pojo.Apply;
import com.bupt.pojo.Code;
import com.bupt.pojo.User;
import com.bupt.service.UserService;
import com.bupt.utils.JsonUtils;
import com.bupt.utils.JwtUtil;
import com.bupt.utils.Sendmail;
import org.apache.commons.codec.binary.Hex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@RestController
@RequestMapping("/user")
public class UserController {
//Controller层调Service层
@Autowired
@Qualifier("UserServiceImpl")
private UserService userService;
@RequestMapping("/login")
public String Login(@RequestBody User user, HttpServletRequest request, HttpServletResponse response){
System.out.println("进入了登录方法!!!");
String testName = user.getUserName();
String testPassword = user.getUserPassword();
String testEmail = user.getUserEmail();
if(testName == null && testEmail == null)
return JsonUtils.getJson("accountEmpty!");
if(testPassword == null)
return JsonUtils.getJson("passwordEmpty!");
User me = userService.queryUserByName(testName);
if(me == null)
me = userService.queryUserByEmail(testEmail);
if(me == null)
return JsonUtils.getJson("noUser");
if(me != null && me.getUserPassword().length() == 48 && verify(testPassword, me.getUserPassword())){
HttpSession session = request.getSession();
session.setAttribute("UserInfo",me);
User userInfo =(User) session.getAttribute("UserInfo");
//token
//添加token,后续做验证
//注册
String token = JwtUtil.sign(me.getUserName(), me.getUserPassword());
if (token !=null){
session.setAttribute("token",token);
System.out.println(session.getAttribute("token"));
// Cookie cookie = new Cookie("_COOKIE_NAME", token);
// cookie.setMaxAge(3600);
// cookie.setPath("/");
// response.addCookie(cookie);
}
System.out.println("token:"+token);
System.out.println("Cookie的信息:");
Cookie[] cookies = request.getCookies();
// for (int i = 0; i < cookies.length; i++) {
// System.out.println(cookies[i]);
// }
System.out.println(userInfo.toString());
System.out.println(userInfo.toString());
return JsonUtils.getJson("true");
}
return JsonUtils.getJson("passwordFalse");
}
@PostMapping("test")
public String getsessionId(@RequestBody User user, HttpServletRequest request){
HttpSession session = request.getSession();
User testuser = userService.queryUserByName(user.getUserName());
session.setAttribute("ID",testuser);
System.out.println("进入了sessionID测试方法!");
Object userId = session.getAttribute("ID");
System.out.println(userId);
return JsonUtils.getJson("true");
}
@RequestMapping("/test2")
public void testSessionID(HttpServletRequest request){
System.out.println("进入了test2测试方法!");
HttpSession session = request.getSession();
Object userId = session.getAttribute("ID");
System.out.println(userId);
}
@PostMapping("/logout")
@ResponseBody
public String Logout(HttpServletRequest request)
{
request.getSession().invalidate();
// Cookie[] cookies = request.getCookies();
// for (int i = 0; i < cookies.length; i++) {
// if (cookies[i].getName().equals("_COOKIE_NAME")){
// cookies[i].setMaxAge(0);
// break;
// }
// }
return JsonUtils.getJson("Logout");
}
@PostMapping("/register")
public String Register(@RequestBody User user,HttpServletRequest request) throws NoSuchAlgorithmException
{
System.out.println("进入了注册方法!");
System.out.println(user.toString());
String testName = user.getUserName();
String testPassword = user.getUserPassword();
String testEmail = user.getUserEmail();
// String testName = "A";
// String testPassword = "12345678";
// String testEmail = "ABC@bupt.cn";
int CheckName = userService.checkName(testName);
int CheckEmail = userService.checkEmail(testEmail);
String regEx = "[ `~!@#$%^&*()+=|{}':;',/\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]|\n|\r|\t";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(testName);
if(m.find() || testName.indexOf("\\") >=0)
{
return JsonUtils.getJson("userNameIllegal");
}
if (!testEmail.matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+"))
{
return JsonUtils.getJson("emailIllegal");
}
else if( CheckName != 0)
{
return JsonUtils.getJson("nameRepeat");
}else if( CheckEmail != 0)
{
return JsonUtils.getJson("emailRepeat");
}else if (testPassword.length()<6||testPassword.length()>16)
{
return JsonUtils.getJson("passwordIllegal");
}
m = p.matcher(testPassword);
if(m.find() || testPassword.indexOf("\\") >=0)
{
return JsonUtils.getJson("passwordIllegal");
}
System.out.println("都合法!");
String md5Pass = generate(testPassword);
System.out.println("加密后的密码:"+md5Pass);
int result = userService.register(testName,testEmail,md5Pass);
System.out.println(result);
if(result==1) {
System.out.println("准备创建文件夹");
File file1=new File("C:\\Users\\darkerg\\Desktop\\savefile"+"\\"+testName);
if (!file1.exists()){
file1.mkdir();
}
return JsonUtils.getJson("registerSuccess");
}
return JsonUtils.getJson("registerFalse");
}
@PostMapping("/apply")
public String Apply(@RequestBody Apply apply, HttpServletRequest request)
{
HttpSession session = request.getSession();
User userInfo = (User) session.getAttribute("UserInfo");
int userId = userInfo.getUserId();
double testApplySize = apply.getApplySize();
User me=userService.queryUserById(userId);
String testUserName = me.getUserName();
// 判断是否有未处理的内存申请消息,0表示无,1表示有
if(me.isUserStatus()) {
return JsonUtils.getJson("alreadyApply");
}
int result = userService.apply(testApplySize,userId,testUserName);
if(result == 1)
{
return JsonUtils.getJson("applySuccess");
}
return JsonUtils.getJson("applyFalse");
}
@PostMapping("/forgetpwd")
public String forgetpwd(@RequestBody User user,HttpServletRequest request){
String userEmail = user.getUserEmail();
User user1 = userService.queryUserByEmail(userEmail);
if (user1==null){
return JsonUtils.getJson("not exist");
}else {
//生产六位随机数
String sjs=getRandomString(5);
//放到session中
HttpSession session = request.getSession();
session.setAttribute("checkNum",sjs);
session.setAttribute("UserInfo",user1);
//给用户发送一封邮件
//我们使用线程来专门发送邮件,防止出现耗时,和网站注册人数过多的情况
Sendmail send = new Sendmail(user1,sjs);
//启动线程,线程启动之后,就会执行Run方法来发送邮件
send.start();
return JsonUtils.getJson("success");
}
}
public static String getRandomString(int length){
String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random=new Random();
StringBuffer sb=new StringBuffer();
for(int i=0;i<length;i++){
int number=random.nextInt(62);
sb.append(str.charAt(number));
}
return sb.toString();
}
@PostMapping("verifynum")
public String verifynum(@RequestBody Code code, HttpServletRequest request){
String sjs = code.getSjs();
System.out.println(sjs);
HttpSession session = request.getSession();
String checknum = (String) session.getAttribute("checkNum");
System.out.println(checknum);
if(!sjs.equals(checknum)){
return JsonUtils.getJson("false");
}
return JsonUtils.getJson("success");
//验证
}
@RequestMapping("changepwd")
public String changePwd(@RequestBody User user, HttpServletRequest request){
String newPwd = user.getUserPassword();
HttpSession session = request.getSession();
User userInfo = (User) session.getAttribute("UserInfo");
String userEmail = userInfo.getUserEmail();
String md5Pass = generate(newPwd);
int i = userService.changePwd(userEmail, md5Pass);
System.out.println(i);
return JsonUtils.getJson("success");
}
@RequestMapping("/getusername")
public String getUserName(HttpServletRequest request){
HttpSession session = request.getSession();
User userInfo =(User) session.getAttribute("UserInfo");
User realUser = userService.queryUserByName(userInfo.getUserName());
return JsonUtils.getJson(realUser);
}
@GetMapping("xmr")
@ResponseBody
public String xmrsb(){
User user1 = userService.queryUserById(1);
User user2 = userService.queryUserById(2);
User user3 = userService.queryUserById(3);
User user4 = userService.queryUserById(4);
User user5 = userService.queryUserById(5);
List<User> userList = new ArrayList<>();
userList.add(user1);
userList.add(user2);
userList.add(user3);
userList.add(user4);
userList.add(user5);
return JsonUtils.getJson(userList);
}
/** 加盐MD5 */
public String generate(String password) {
Random r = new Random();
StringBuilder sb = new StringBuilder(16);
sb.append(r.nextInt(99999999)).append(r.nextInt(99999999));
int len = sb.length();
if (len < 16) {
for (int i = 0; i < 16 - len; i++) {
sb.append("0");
}
}
String salt = sb.toString();
password = md5Hex(password + salt);
char[] cs = new char[48];
for (int i = 0; i < 48; i += 3) {
cs[i] = password.charAt(i / 3 * 2);
char c = salt.charAt(i / 3);
cs[i + 1] = c;
cs[i + 2] = password.charAt(i / 3 * 2 + 1);
}
return new String(cs);
}
/** 校验加盐后是否和原文一致 */
public boolean verify(String password, String md5) {
char[] cs1 = new char[32];
char[] cs2 = new char[16];
for (int i = 0; i < 48; i += 3) {
cs1[i / 3 * 2] = md5.charAt(i);
cs1[i / 3 * 2 + 1] = md5.charAt(i + 2);
cs2[i / 3] = md5.charAt(i + 1);
}
String salt = new String(cs2);
return md5Hex(password + salt).equals(new String(cs1));
}
/** 获取十六进制字符串形式的MD5摘要 */
private String md5Hex(String src) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] bs = md5.digest(src.getBytes());
return new String(new Hex().encode(bs));
} catch (Exception e) {
return null;
}
}
}
②FileController
package com.bupt.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.bupt.tools.EncryptAndDecrypt;
import com.bupt.tools.FiletoByte;
import com.bupt.utils.JsonUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.bupt.pojo.File;
import com.bupt.pojo.User;
import com.bupt.service.FileService;
import com.bupt.service.UserService;
@RestController
@RequestMapping("/file")
public class FileController
{
@Resource
@Autowired
private FileService fileservice;
@Resource
@Autowired
private UserService uservice;
@GetMapping("/list")
@ResponseBody
public String showupload(HttpServletRequest request)
{
System.out.println("进入获取文件列表");
HttpSession session = request.getSession();
User userInfo = (User) session.getAttribute("UserInfo");
User me=uservice.queryUserById(userInfo.getUserId());
List<File> fileList=uservice.getFileById(userInfo.getUserId());
System.out.println(JsonUtils.getJson(fileList));
return JsonUtils.getJson(fileList);
}
@PostMapping("/upload")
@ResponseBody
public String UpLoad(@RequestParam("file")MultipartFile file,HttpServletRequest request) throws Exception
{
int result = 0;
String name = file.getOriginalFilename();
int indexOfPoint = name.lastIndexOf('.');
if(indexOfPoint == -1) {
indexOfPoint = name.length();
}
String fileName = name.substring(0,indexOfPoint);
String fileType = name.substring(indexOfPoint+1);
HttpSession session = request.getSession();
User userInfo = (User)session.getAttribute("UserInfo");
String ownerStr = userInfo.getUserName();
int owner = userInfo.getUserId();
User u=uservice.queryUserById(owner);
System.out.println(fileName);
System.out.println(fileType);
System.out.println(ownerStr);
File exist_file = fileservice.GetFileByName(fileName,fileType,owner);
System.out.println(exist_file);
double size = (double)file.getSize()/1000000;
if(exist_file != null) {
return "File already exists motherxxxxx";
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
String time = sdf.format(now);
String hash = DigestUtils.md5Hex(file.getBytes());
System.out.println("准备上传");
String path = "C:\\Users\\darkerg\\Desktop\\savefile"+"\\"+u.getUserName()+"\\"+name; //需要改
if(u.getUserUsage()+size > u.getUserStorage())
{
result = 0;
return "storage is not enough";
}
fileservice.AddStorage(owner, size);
//java.io.File uploadpath = new java.io.File(path);
EncryptAndDecrypt.DESEncrypt(file, path, u.getUserKey());
result = fileservice.InsertFileInfo(fileName, fileType, size, time, owner, hash, path);
System.out.println("upload result="+result);
return "" + (result == 1);
}
@PostMapping ("/delete")
public String DeleteFile(@RequestBody File file, HttpServletRequest request)
{
HttpSession session = request.getSession();
User user =(User) session.getAttribute("UserInfo");
int userId = user.getUserId();
int fileId = file.getFileId();
File targetFile = fileservice.GetFileById(fileId);
// File targetFile = fileservice.GetFileByName(file.getFileName(), file.getFileType(), userId);
double file_size = targetFile.getFileSize();
// if(file_size<=0) return JsonUtils.getJson("delete failed!!");
// if(file_size > user.getUserUsage()) {
// file_size = user.getUserUsage();
// }
if(fileservice.SubStorage(userId, file_size) == 0)
return JsonUtils.getJson("change user's storage failed!!");
if(fileservice.DeleteFile(targetFile.getFileId()) == 0)
return JsonUtils.getJson("delete from mysql failed!!");
String path = "C:\\Users\\darkerg\\Desktop\\savefile"+"\\"+user.getUserName()+"\\"+file.getFileName()+"."+file.getFileType();
java.io.File local_file = new java.io.File(path);
if(!local_file.delete())
return JsonUtils.getJson("delete from service failed!!");
return JsonUtils.getJson("Delete Successfully!!");
}
@RequestMapping(value="/download",method=RequestMethod.POST,produces = {"application/json;charset=UTF-8"}) //匹配的是href中的download请求
public ResponseEntity<byte[]> DownloadFile(HttpServletRequest request ,@RequestBody File file) throws Exception {
ResponseEntity<byte[]> responseEntity = null;
//得到file类
HttpSession session = request.getSession();
User user =(User) session.getAttribute("UserInfo");
int userId = user.getUserId();
File select_file =fileservice.GetFileByName(file.getFileName(),file.getFileType(),userId);
String fileName = select_file.getFileName() + "." + select_file.getFileType();
String myFileName=new String(fileName.getBytes("utf-8"),"iso-8859-1");
int index = select_file.getFilePath().lastIndexOf("\\");
String username = select_file.getFilePath().substring(34, index); //按下面路径(209行)数数
System.out.println("username是:"+username);
User u=uservice.queryUserByName(username);
String path = "C:\\Users\\darkerg\\Desktop\\savefile" +"\\"+ u.getUserName() + "\\" + fileName;
java.io.File file1 = new java.io.File(path);
if(!file1.exists()) {
return null;
}
java.io.File outFile = new java.io.File("C:\\Users\\darkerg\\Desktop\\savefile\\" + u.getUserName() + "\\" + "temp");
if(!outFile.exists()) {
outFile.mkdir();
}
String outPath = "C:\\Users\\darkerg\\Desktop\\savefile" +"\\"+ u.getUserName() + "\\" + "temp\\" + fileName; //解密后文件存放路径
EncryptAndDecrypt.DESDecrypt(file1, outPath, u.getUserKey());
byte[] hash = FiletoByte.getBytesByFile(outPath);
System.out.println(hash);
System.out.println(select_file.getFileHash().getBytes());
HttpHeaders headers=new HttpHeaders();
headers.setContentDispositionFormData("attachment", myFileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
java.io.File de_file = new java.io.File(outPath);
responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(de_file),headers,HttpStatus.CREATED);
de_file.delete();
return responseEntity;
}
}
③GroupController
package com.bupt.controller;
import com.bupt.pojo.File;
import com.bupt.pojo.Group;
import com.bupt.pojo.User;
import com.bupt.service.FileService;
import com.bupt.service.GroupService;
import com.bupt.service.UserService;
import com.bupt.tools.EncryptAndDecrypt;
import com.bupt.tools.FiletoByte;
import com.bupt.utils.JsonUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("/group")
public class GroupController {
//Controller层调Service层
@Autowired
@Qualifier("GroupServiceImpl")
private GroupService groupService;
@Autowired
@Qualifier("UserServiceImpl")
private UserService uservice;
@Autowired
@Qualifier("FileServiceImpl")
private FileService fileservice;
@RequestMapping("/list")
public String showGroups(HttpServletRequest request){
System.out.println("进入了grouplist");
HttpSession session = request.getSession();
User userInfo = (User) session.getAttribute("UserInfo");
List<Group> GroupList = null;
try {
GroupList = groupService.getGroups(userInfo.getUserId());
System.out.println(GroupList);
} catch (Exception e) {
e.printStackTrace();
}
if (GroupList != null){
return JsonUtils.getJson(GroupList);
}else{
return JsonUtils.getJson("empty");
}
}
@PostMapping("/filelist")
@ResponseBody
public String showupload(@RequestBody Group group,HttpServletRequest request)
{
System.out.println("进入获取文件列表");
int testGroupId = group.getGroupId();
Group realGroup = groupService.getGroupById(testGroupId);
System.out.println(realGroup);
HttpSession session = request.getSession();
session.setAttribute("group",realGroup);
Group test1 = (Group) session.getAttribute("group");
System.out.println("test1==="+test1);
// User me=uservice.queryUserById(userInfo.getUserId());
List<File> fileList = groupService.GetFileByGroup(testGroupId);
System.out.println(testGroupId);
System.out.println(JsonUtils.getJson(fileList));
return JsonUtils.getJson(fileList);
}
@RequestMapping("/manageList")
public String showGroupsManage(HttpServletRequest request){
System.out.println("进入了managerlist");
HttpSession session = request.getSession();
User userInfo = (User) session.getAttribute("UserInfo");
List<Group> GroupManageList = groupService.getGroupsManage(userInfo.getUserId());
return JsonUtils.getJson(GroupManageList);
}
@RequestMapping("/registerGroup")
public String RegisterGroup(HttpServletRequest request) {
HttpSession session = request.getSession();
User userInfo = (User) session.getAttribute("UserInfo");
// 随机生成7位随机数作为群Id
int groupId = (int)(Math.random()*(9999999-1000000+1))+1000000;
// 检验此群Id是否已经使用,若已经使用,则重新生成群Id
int test = groupService.getGroupNumById(groupId);
while(test == 1){
groupId = (int)(Math.random()*(9999999-1000000+1))+1000000;
test = groupService.getGroupNumById(groupId);
}
// 创建群组
int result1 = groupService.registerGroup(userInfo.getUserId(), groupId);
// 群组管理员在创建成功群组后加入群组
int result2 = groupService.addGroup(userInfo.getUserId(), groupId);
if(result1 == 1 && result2 == 1) {
java.io.File file1=new java.io.File("C:\\Users\\darkerg\\Desktop\\savefile"+"\\"+userInfo.getUserName()+"\\"+groupId);
if (!file1.exists()){
file1.mkdir();
}
return JsonUtils.getJson(groupId);
}
return JsonUtils.getJson("Fail");
}
@RequestMapping("/addGroup")
public String AddGroup(@RequestBody Group group, HttpServletRequest request){
//直接获取userId和通过输入获得用户要加入的群组的groupId
HttpSession session = request.getSession();
User userInfo = (User) session.getAttribute("UserInfo");
int groupId = group.getGroupId();
int groupExist = groupService.getGroupNumById(groupId);
if(groupExist == 0){
return JsonUtils.getJson("noGroup");
}
// int groupIn = groupService.judgeGroupById(userInfo.getUserId(),groupId);
// if(groupIn != 0){
// return JsonUtils.getJson("inGroup");
// }
int ad = groupService.addGroup(userInfo.getUserId(),groupId);
if(ad == 1)
return JsonUtils.getJson("Success");
return JsonUtils.getJson("Fail");
}
@PostMapping("/upload")
@ResponseBody
public String UpLoad(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception
{
//得到文件名
int result = 0;
String name = file.getOriginalFilename();
int indexOfPoint = name.lastIndexOf('.');
if(indexOfPoint == -1) {
indexOfPoint = name.length();
}
String fileName = name.substring(0,indexOfPoint);
String fileType = name.substring(indexOfPoint+1);
//获得user数据
HttpSession session = request.getSession();
User userInfo = (User)session.getAttribute("UserInfo");
String ownerStr = userInfo.getUserName();
int owner = userInfo.getUserId();
User u=uservice.queryUserById(owner);
System.out.println(u.getUserName());
//获得群组
Group group =(Group) session.getAttribute("group");
int groupId = group.getGroupId();
System.out.println("getgroupId==="+groupId);
File exist_file = groupService.GetFileById(fileName,fileType,groupId,owner);
double size = (double)file.getSize()/1000000;
if(exist_file != null) {
return JsonUtils.getJson("already exist");
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
String time = sdf.format(now);
String hash = DigestUtils.md5Hex(file.getBytes());
System.out.println("准备上传");
String path = "C:\\Users\\darkerg\\Desktop\\savefile"+"\\"+u.getUserName()+"\\"+groupId+"\\"+name; //需要改
if(group.getGroupUsage()+size > group.getGroupStorage())
{
result = 0;
return JsonUtils.getJson("storage is not enough");
}
groupService.AddStorage(groupId, size);
//java.io.File uploadpath = new java.io.File(path);
EncryptAndDecrypt.DESEncrypt(file, path, u.getUserKey());
result = groupService.InsertFileInfo(fileName, fileType, size, time, owner, groupId, hash, path);
System.out.println("upload result="+result);
return "" + (result == 1);
}
@PostMapping ("/delete")
public String DeleteFile(@RequestBody File file, HttpServletRequest request)
{
// //获取user数据
// HttpSession session = request.getSession();
// User user =(User) session.getAttribute("UserInfo");
// Group group = (Group)session.getAttribute("group");
// int userId = user.getUserId();
//通过Session获取groupId
HttpSession session = request.getSession();
Group group =(Group) session.getAttribute("group");
//拿到fileId
int fileId = file.getFileId();
System.out.println("FileId是:"+fileId);
//通过fileId找到gruopId,先拿到这个targetFile
File targetFile = fileservice.GetGroupFileById(fileId,group.getGroupId());
System.out.println("目标文件名是:"+targetFile);
//通过File获得groupId
int groupId = targetFile.getFileGroup();
//获取groupId后,拿到这个详细信息中的,groupManagerId
Group targetGroup = groupService.getGroupInfoById(groupId);
//拿到groupManagerId
int groupManagerId = targetGroup.getGroupManagerId();
//获取SaveFile下第一级文件名:groupManager的名字
User user = uservice.queryUserById(groupManagerId);
String groupManagerName = user.getUserName();
//文件大小
double file_size = targetFile.getFileSize();
// if(file_size > group1.getGroupUsage()) {
// file_size = group1.getGroupUsage();
// }
if(groupService.SubStorage(groupId, file_size) == 0)
return JsonUtils.getJson("failed1");
if(groupService.DeleteFile(targetFile.getFileId()) == 0)
return JsonUtils.getJson("failed2");
String path = "C:\\Users\\darkerg\\Desktop\\savefile"+"\\"+groupManagerName+"\\"+groupId+"\\"+file.getFileName()+"."+file.getFileType();
java.io.File local_file = new java.io.File(path);
if(!local_file.delete())
return JsonUtils.getJson("failed3");
return JsonUtils.getJson("success");
}
@RequestMapping(value="/download",method=RequestMethod.POST,produces = {"application/json;charset=UTF-8"}) //匹配的是href中的download请求
public ResponseEntity<byte[]> DownloadFile(HttpServletRequest request , @RequestBody File file) throws Exception {
ResponseEntity<byte[]> responseEntity = null;
//通过Session获取groupId
HttpSession session = request.getSession();
Group group =(Group) session.getAttribute("group");
//拿到fileId
int fileId = file.getFileId();
System.out.println("FileId是:"+fileId);
//通过fileId找到gruopId,先拿到这个targetFile
File targetFile = fileservice.GetGroupFileById(fileId,group.getGroupId());
System.out.println("目标文件名是:"+targetFile);
//通过File获得groupId
int groupId = targetFile.getFileGroup();
//获取groupId后,拿到这个详细信息中的,groupManagerId
Group targetGroup = groupService.getGroupInfoById(groupId);
//拿到groupManagerId
int groupManagerId = targetGroup.getGroupManagerId();
//获取SaveFile下第一级文件名:groupManager的名字
User user_manager = uservice.queryUserById(groupManagerId);
String groupManagerName = user_manager.getUserName();
System.out.println(groupId);
System.out.println(groupManagerName);
//获取这个文件是谁他么上传的
int file_ownerId = targetFile.getFileOwner();
User owner_user = uservice.queryUserById(file_ownerId);
String allFileName = targetFile.getFileName()+"."+targetFile.getFileType();
String targetDownloadFile=new String(allFileName.getBytes("utf-8"),"iso-8859-1");
String path = "C:\\Users\\darkerg\\Desktop\\savefile" +"\\"+ groupManagerName + "\\" +groupId+"\\" +targetDownloadFile;
System.out.println(path);
java.io.File file1 = new java.io.File(path);
if(!file1.exists()) {
return null;
}
java.io.File outFile = new java.io.File("C:\\Users\\darkerg\\Desktop\\savefile\\" + groupManagerName +"\\"+groupId+ "\\" + "temp");
if(!outFile.exists()) {
outFile.mkdir();
}
String outPath = "C:\\Users\\darkerg\\Desktop\\savefile" +"\\"+ groupManagerName +"\\"+groupId+ "\\" + "temp\\" + targetDownloadFile; //解密后文件存放路径
System.out.println(groupManagerName);
System.out.println(groupId);
System.out.println(outPath);
EncryptAndDecrypt.DESDecrypt(file1, outPath, owner_user.getUserKey());
byte[] hash = FiletoByte.getBytesByFile(outPath);
HttpHeaders headers=new HttpHeaders();
headers.setContentDispositionFormData("attachment", targetDownloadFile);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
java.io.File de_file = new java.io.File(outPath);
responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(de_file),headers, HttpStatus.CREATED);
de_file.delete();
return responseEntity;
}
@RequestMapping("/entergroup")
private String enterGroup(@RequestBody Group group,HttpServletRequest request){
int groupId = group.getGroupId();
System.out.println("++++++++++++++++"+groupId);
Group realGroup = groupService.getGroupById(groupId);
HttpSession xmrsession = request.getSession();
xmrsession.setAttribute("xmrgroup", realGroup);
return JsonUtils.getJson(realGroup);
}
@RequestMapping("/getgroupinfo")
public String getGroupInfo(HttpServletRequest request){
HttpSession session = request.getSession();
Group group =(Group) session.getAttribute("xmrgroup");
return JsonUtils.getJson(group);
}
}
④ManagerController
package com.bupt.controller;
import com.bupt.pojo.Apply;
import com.bupt.pojo.Group;
import com.bupt.pojo.User;
import com.bupt.service.GroupService;
import com.bupt.service.ManagerService;
import com.bupt.service.UserService;
import com.bupt.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/mana")
public class ManagerController {
//Controller层调Service层
@Autowired
@Qualifier("ManagerServiceImpl")
private ManagerService managerService;
@Autowired
@Qualifier("UserServiceImpl")
private UserService userService;
@Autowired
@Qualifier("GroupServiceImpl")
private GroupService groupService;
@RequestMapping("/queryalluser")
//获取所有用户列表
public String getAllUser() {
List<User> User = managerService.getAllUsers();
return JsonUtils.getJson(User);
}
@RequestMapping("/queryGroup")
//获取所有群组列表
public String getAllGroup() {
List<Group> gro = managerService.getAllGroups();
return JsonUtils.getJson(gro);
}
@RequestMapping("/queryallapply")
//获取所有申请列表
public String getAllApplies() {
List<Apply> Apply = managerService.getAllApplies();
return JsonUtils.getJson(Apply);
}
@RequestMapping("/setUserstorage")
//设置用户的存储空间为size
public String setUserStorage(@RequestBody User user) {
double Size= user.getUserStorage();
System.out.println(user);
System.out.println(Size);
//找到真实的用户
User targetUser = userService.queryUserByName(user.getUserName());
if (Size < targetUser.getUserUsage())
return JsonUtils.getJson("error");
//申请<已有
int result = managerService.SetUserStorage(targetUser.getUserId(),Size);
//否则,设置存储空间
if (result != 0) {
return JsonUtils.getJson("reset succeeded");
//设置成功
}
else {
return JsonUtils.getJson("reset failed");
}
}
@RequestMapping("/agreeApply")
//同意申请
public String agreeApply(@RequestBody Apply apply) {
System.out.println(apply);
int requestID = apply.getApplyRequestId();
double test_size = apply.getApplySize();
//int result = managerService.AgreeApply(requestID,test_size)* managerService.DeleteApply(requestID);
int result1 = managerService.AgreeApply(requestID, test_size);
int result2 = managerService.DeleteApply(requestID);
System.out.println(result1);
System.out.println(result2);
System.out.println(result1*result2);
if (result1*result2 == 1) {
return JsonUtils.getJson("agree succeeded");
//同意申请成功
}
else {
return JsonUtils.getJson("agree failed");
//同意申请失败
}
}
@RequestMapping("/refuseApply")
//拒绝申请
public String RefuseApply(@RequestBody Apply apply) {
System.out.println(apply);
int requestID = apply.getApplyRequestId();
int result = managerService.RefuseApply(requestID)* managerService.DeleteApply(requestID);
if (result != 0) {
return JsonUtils.getJson("refuse succeeded");
//拒绝申请成功
}
else {
return JsonUtils.getJson("refuse failed");
//拒绝申请失败
}
}
}
8、config集成Swagger配置类
SwaggerConfig
package com.bupt.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Swagger2配置类
* 在与spring boot集成时,放在与Application.java同级的目录下。
* 通过@Configuration注解,让Spring来加载该类配置。
* 再通过@EnableSwagger2注解来启用Swagger2。
*/
@Configuration
@EnableWebMvc
@EnableSwagger2
public class SwaggerConfig {
//接口文档构建配置
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
//通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现
.select()
//所有的接口
.apis(RequestHandlerSelectors.any())
//指定扫描的路径
// .apis(RequestHandlerSelectors.basePackage("com.bupt.controller"))
.build()
.apiInfo(apiInfo());
}
//接口文档信息
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("超级安全云盘Api接口服务列表")
.description("")
.termsOfServiceUrl("http://192.168.100.104:7080")
.version("1.0")
.build();
}
}
9、interceptor下的登录拦截器配置
TokenInterceptor
package com.bupt.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.bupt.utils.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
public class TokenInterceptor implements HandlerInterceptor{
/**
* 拦截器和过滤器的区别
* 1.拦截器针对访问控制器进行拦截
* 及 @RequestMapping(value = {"/test"})
* 简而言说就是访问方法的url
* 应用:可以作为权限的判断,
* 2.过滤器则是针对全局的请求
* 包括:css/js/html/jpg/png/git/...
* 及静态文件
* 20200417 23:13
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("执行方法之前执行这步操作!");
response.setCharacterEncoding("utf-8");
// Cookie cookie=getCookieByName(request,"_COOKIE_NAME");
String token =(String) request.getSession().getAttribute("token");
//如果已经登录,不拦截
if (null != token) {
//验证token是否正确
boolean result = JwtUtil.verify(token);
if (!result) {
return false;
}
return true;
}
//如果没有登录,则跳转到登录界面
else {
response.sendError(202);
//重定向 第一种 调用控制器 方法
// response.sendRedirect(request.getContextPath() + "/user/login");
//重定向 第二种 重定向方法
// request.getRequestDispatcher("WEB-INF/jsp/login.jsp").forward(request, response);
// System.out.println(request.getContextPath());
return false;
/**
* 以下是为了登录成功后返回到刚刚的操作,不跳到主界面
* 实现:通过将请求URL保存到session的beforePath中,然后在登录时判断beforePath是否为空
*/
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
/**
* 根据名字获取cookie
*
* @param request
* @param name cookie名字
* @return
*/
public static Cookie getCookieByName(HttpServletRequest request, String name) {
Map<String, Cookie> cookieMap = ReadCookieMap(request);
if (cookieMap.containsKey(name)) {
Cookie cookie = cookieMap.get(name);
return cookie;
} else {
return null;
}
}
/**
* 将cookie封装到Map里面
*
* @param request
* @return
*/
private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) {
Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
Cookie[] cookies = request.getCookies();
if (null != cookies) {
for (Cookie cookie : cookies) {
cookieMap.put(cookie.getName(), cookie);
}
}
return cookieMap;
}
/**
* 返回信息给客户端
*
* @param response
* @param out
*/
private void responseMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) throws IOException {
response.setContentType("application/json; charset=utf-8");
out.print(JSONObject.toJSONString("message"));
out.flush();
out.close();
}
}
三、resouces下的xml配置文件
1、database.properties
jdbc.driver = com.mysql.jdbc.Driver
#如果使用的是MySQL8.0+,增加一个时区的配置。 &serverTimezone=Asia/Shanghai
jdbc.url = jdbc:mysql://localhost:3306/webpan?useSSL=true&useUnicode=true&characterEncoding=utf-8
jdbc.username =
jdbc.password =
2、mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
<!-- <settings>-->
<!-- <setting name="logImpl" value="STDOUT_LOGGING"/>-->
<!-- </settings>-->
<typeAliases>
<package name="com.bupt.pojo"/>
</typeAliases>
<mappers>
<mapper class="com.bupt.dao.UserMapper"/>
<mapper class="com.bupt.dao.FileMapper"/>
<mapper class="com.bupt.dao.GroupMapper"/>
<mapper class="com.bupt.dao.ManagerMapper"/>
</mappers>
</configuration>
3、spring-dao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--关联数据库配置文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!--连接池
dbcp: 半自动化操作,不能自动连接
c3p0: 自动化操作(自动化的加载配置文件,斌企鹅可以自动设置到对象中。
druid:
hikari:
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--绑定Mybatis的配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!--配置dao接口扫描包,动态的实现了Dao接口可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入sqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要扫描的dao包-->
<property name="basePackage" value="com.bupt.dao"/>
</bean>
</beans>
4、spring-service.xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--扫描service下的包-->
<context:component-scan base-package="com.bupt.service"/>
<!--将我们的所有业务类,注入到Spring,可以通过配置,或者注解实现-->
<bean id="UserServiceImpl" class="com.bupt.service.UserServiceImpl">
<property name="userMapper" ref="userMapper"/>
</bean>
<bean id="FileServiceImpl" class="com.bupt.service.FileServiceImpl">
<property name="fileMapper" ref="fileMapper"/>
</bean>
<bean id="GroupServiceImpl" class="com.bupt.service.GroupServiceImpl">
<property name="groupMapper" ref="groupMapper"/>
</bean>
<bean id="ManagerServiceImpl" class="com.bupt.service.ManagerServiceImpl">
<property name="managerMapper" ref="managerMapper"/>
</bean>
<!--声明式事务配置-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--AOP横切事务支持-->
</beans>
5、spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--注解驱动-->
<mvc:annotation-driven/>
<!--静态资源过滤-->
<mvc:default-servlet-handler/>
<!--扫描包:controller-->
<context:component-scan base-package="com.bupt.controller"/>
<bean class="com.bupt.config.SwaggerConfig"/>
<!-- 静态资源 -->
<!-- <mvc:resources mapping="/static/**" location="/static/" />-->
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />
<!--让Spring MVC不处理静态资源 .css .js .html .mp3 .mp4-->
<mvc:default-servlet-handler />
<!--解决json 乱码配置-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--文件上传的配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--请求的编码格式,必须和jsp的pageEncoding属性一致,以便正确的读取表单的内容,默认为ISO-8859-1 -->
<property name="defaultEncoding" value="utf-8"/>
<!--上传文件大小上限,单位为字节(10485760=10M)-->
<property name="maxUploadSize" value="104865760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
<mvc:cors>
<mvc:mapping path="/**"
allowed-origins="http://localhost:8080"
allowed-methods="POST, GET, OPTIONS, DELETE, PUT"
allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
allow-credentials="true"/>
</mvc:cors>
<!--自定义拦截器-->
<mvc:interceptors>
<!-- 验证是否登录 通过cookie -->
<mvc:interceptor>
<!-- 拦截所有mvc控制器 -->
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/user/login"/>
<mvc:exclude-mapping path="/user/logout"/>
<mvc:exclude-mapping path="/user/register"/>
<mvc:exclude-mapping path="/user/forgetpwd"/>
<mvc:exclude-mapping path="/user/verifynum"/>
<mvc:exclude-mapping path="/user/changepwd"/>
<mvc:exclude-mapping path="/swagger-ui.html"/>
<mvc:exclude-mapping path="/api=docs"/>
<bean class="com.bupt.interceptor.TokenInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
</beans>
6、applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
</beans>
7、web下的web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0">
<!--配置DispatcherServlet: 这个是SpringMVC的核心,请求分发器,前端控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--DispatcherServlet要绑定spring的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<!--启动级别 1-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--/: 只匹配所有的请求,不会去匹配jsp页面-->
<!--/*: 配所有的请求,包括jsp页面-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
<!--跨域-->
<!--加入跨域过滤器配置-->
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
四、本次项目参考技术
1、Swagger
https://blog.csdn.net/caiqing116/article/details/85146870
2、Cookie、Session、Token的理解
https://www.cnblogs.com/moyand/p/9047978.html