需求
對P2P項目合同進行管理,在WEB項目中實現對文件的上傳下載和刪除操作。
● 有一些債權:投資人有該債務的權利
注:通常隱含的意思就是:一筆借款常被稱為一個債權。
● 一個債權會有一個合同
● 合同是pdf文件
● 債權是債務的對應詞,但是在P2P項目中,我們管理的債權,以及合同一般指的是借款人的信息,所以在我們下面創建的creditor_info表中存的是借款人信息
● 實現對pdf文件上傳、下載、刪除
● 熟練一下Springboot+thymeleaf
① 創建數據庫fastdfs
② 在該庫下創建creditor_info表
CREATE TABLE `creditor_info` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
`realName` varchar(35) DEFAULT NULL COMMENT '債權借款人姓名',
`idCard` varchar(18) DEFAULT NULL COMMENT '債權借款人身份證',
`address` varchar(150) DEFAULT NULL COMMENT '債權借款人地址',
`sex` int(1) DEFAULT NULL COMMENT '1男2女',
`phone` varchar(11) DEFAULT NULL COMMENT '債權借款人電話',
`money` decimal(10,2) DEFAULT NULL COMMENT '債權借款人借款金額',
`groupName` varchar(10) DEFAULT NULL COMMENT '債權合同所在組',
`remoteFilePath` varchar(150) DEFAULT NULL COMMENT '債權合同所在路徑',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
⒉ 開發環境搭建
① 創建SpringBoot項目10-fastdfs-web,添加Web和Thymeleaf依賴
② 在pom.xml文件中添加Mybatis依賴及MySQL依賴
<!-- 加載mybatis整合springboot -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<!--在springboot的父工程中沒有指定版本,我們需要手動指定-->
<version>1.3.2</version>
</dependency>
<!-- MySQL的jdbc驅動包 -->
<dependency>
<groupId>mysql</groupId>
<!--在springboot的父工程中指定了版本,我們就不需要手動指定了-->
<artifactId>mysql-connector-java</artifactId>
</dependency>
③ 在pom.xml文件中添加resources,指定編譯的位置
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
<!--如果存在jsp,需要指定jsp文件編譯的位置-->
</resources>
④ 在SpringBoot主配置文件application.properties中添加數據庫配置信息
#數據庫的連接配置信息
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.235.128:3306/fastdfs?useUnicode=true&characterEncoding=utf8&useSSL=false
⑤ 使用Mybatis反向工程,生成實體類及mapper映射(參照SpringBoot附錄教程)
A、在pom.xml文件中添加反向工程插件
<!--mybatis代碼自動生成插件-->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<configuration>
<!--配置文件的位置-->
<configurationFile>GeneratorMapper.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
B、 從03-springboot-web中復制GeneratorMapper.xml到當前項目下
C、 修改GeneratorMapper.xml配置文件內容
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!-- 指定連接數據庫的JDBC驅動包所在位置,指定到你本機的完整路徑 -->
<classPathEntry location="D:/repository/mysql/mysql-connector-java/8.0.13/mysql-connector-java-8.0.13.jar"/>
<!-- 配置table表信息內容體,targetRuntime指定采用MyBatis3的版本 -->
<context id="tables" targetRuntime="MyBatis3">
<!-- 抑制生成注釋,由于生成的注釋都是英文的,可以不讓它生成 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- 配置數據庫連接信息 注意:使用高版本的驅動 url后面應該加屬性nullCatalogMeansCurrent=true,否則生成有問題 -->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.235.128:3306/fastdfs?nullCatalogMeansCurrent=true"
userId="root"
password="123456">
</jdbcConnection>
<!-- 生成model類,targetPackage指定model類的包名, targetProject指定生成的model放在eclipse的哪個工程下面-->
<javaModelGenerator targetPackage="com.bjpowernode.fastdfs.model" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="false" />
</javaModelGenerator>
<!-- 生成MyBatis的Mapper.xml文件,targetPackage指定mapper.xml文件的包名, targetProject指定生成的mapper.xml放在eclipse的哪個工程下面 -->
<sqlMapGenerator targetPackage="com.bjpowernode.fastdfs.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 生成MyBatis的Mapper接口類文件,targetPackage指定Mapper接口類的包名, targetProject指定生成的Mapper接口放在eclipse的哪個工程下面 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.bjpowernode.fastdfs.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 數據庫表名及對應的Java模型類名 -->
<table tableName="creditor_info"
domainObjectName="CreditorInfo"
enableCountByExample="false"
enableUpdateByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
selectByExampleQueryId="false"/>
</context>
</generatorConfiguration>
D、雙擊生成
⑥ 創建相關的包和類
在com.bjpowernode.fast包下創建controller ,service 包,及其子包impl
創建CreditorInfoController類
創建CreditorInfoService接口
創建CreditorInfoServiceImpl實現類
① 在CreditorInfoController類中創建index方法,將CreditorInfoService注入到controller中
@Controller
public class CreditorInfoController {
@Autowired
private CreditorInfoService creditorInfoService;
@GetMapping("/fastdfs/index")
public String index(Model model){
List<CreditorInfo> creditorInfoList = creditorInfoService.getAllCreditorInfo();
model.addAttribute("creditorInfoList",creditorInfoList);
//模板頁面,不是jsp
return "index";
}
}
② 在CreditorInfoService中提供getAllCreditorInfo方法
public interface CreditorInfoService {
/**
* 獲取所有債權信息
* @return
*/
List<CreditorInfo> getAllCreditorInfo();
}
③ 在CreditorInfoServiceImpl中對getAllCreditorInfo方法進行實現
@Service
public class CreditorInfoServiceImpl implements CreditorInfoService {
@Autowired
private CreditorInfoMapper creditorInfoMapper;
@Override
public List<CreditorInfo> getAllCreditorInfo() {
return creditorInfoMapper.selectAllCreditorInfo();
}
}
④ 因為是SpringBoot項目,所以需要在Mapper接口上加一個Mapper注解
@Mapper
public interface CreditorInfoMapper {
⑤ 在CreditorInfoMapper類中添加selectAllCreditorInfo方法
List<CreditorInfo> selectAllCreditorInfo();
⑥ 在IDEA中安裝free Mybatis插件
該插件可以通過點擊Mapper接口中的方法,進入到.xml文件
A、 SettingsàpluginsàBrowse repositories
B、 在插件庫中搜索,free mybatis安裝
C、 插件安裝完畢,需要重啟IDEA
⑦ 在CreditorInfoMapper.xml文件中添加SQL語句
<select id="selectAllCreditorInfo" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from creditor_info
</select>
⑧ 展示頁面的設計
A、 在項目的templates目錄下創建index.html
B、 百度搜索bootstrap表格,挑選自己喜歡風格的表格,將代碼拷貝到index.html中
我這里使用的是http://www.dabaquan.cn/try/try.php?
filename=bootstrap3-table-striped表格進行改寫
C、 在html標簽上加上Thymeleaf的命名空間
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
D、 修改index.html內容
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>債權合同管理</title>
<link rel="stylesheet" th:href="@{/css/bootstrap-3.3.7.min.css}">
<script th:src="@{/js/jquery-2.1.1.min.js}"></script>
<script th:src="@{/js/bootstrap-3.3.7.min.js}"></script>
</head>
<body>
<table class="table table-striped">
<caption>債權合同信息列表</caption>
<thead>
<tr>
<th>序號</th>
<th>債權借款人姓名</th>
<th>債權借款人身份證</th>
<th>債權借款人住址</th>
<th>債權借款人手機號</th>
<th>債權借款人性別</th>
<th>債權借款人借款金額</th>
</tr>
</thead>
<tbody>
<tr th:each="creditorInfo:${creditorInfoList}">
<td th:text="${creditorInfoStat.count}"></td>
<td th:text="${creditorInfo.realname}"></td>
<td th:text="${creditorInfo.idcard}"></td>
<td th:text="${creditorInfo.address}"></td>
<td th:text="${creditorInfo.phone}"></td>
<td th:text="${creditorInfo.sex == 1 ?'男':'女'}"></td>
<td th:text="${creditorInfo.money}"></td>
</tr>
</tbody>
</table>
</body>
</html>
注意:我們從網絡上拷貝過來的內容css,js等是聯網獲取的,我們這里可以從04-FastDFS\resources獲取,并放在項目的static的相關目錄下,在頁面上引用
⑨ 向數據庫中加幾條數據
⑩ 啟動項目,訪問http://localhost:8080/fastdfs/index 查看效果
? 調整頁面樣式
<body style="margin: 50px">
4. 功能實現-為某一個債權合同上傳文件
① 在index.html中添加操作列
<th>合同管理</th>
<td>
<!--為哪個合同上傳,需要將合同的id傳遞過去-->
<a th:href="@{'/fastdfs/toUpload?id=' + ${creditorInfo.id}}">上傳</a>
下載
刪除
</td>
② 在CreditorController中添加跳轉到上傳頁面的方法
@GetMapping("/fastdfs/toUpload")
public String toUpload(Model model, @RequestParam("id") Integer id){
model.addAttribute("id",id);
return "upload";
}
③ 在templates下創建upload.html頁面
在網上搜索bootstrap表單,并對其內容進行修改,我這里使用的是
http://www.dabaquan.cn/try/try2.php?filename=bootstrap3-form-inline
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>債權合同上傳</title>
<link rel="stylesheet" th:href="@{/css/bootstrap-3.3.7.min.css}">
<script th:src="@{/js/jquery-2.1.1.min.js}"></script>
<script th:src="@{/js/bootstrap-3.3.7.min.js}"></script>
</head>
<body>
<form th:action="@{/fastdfs/upload}" class="form-inline" role="form" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="sr-only" for="fileName">文件輸入</label>
<input type="file" id="fileName" name="fileName">
</div>
<input type="hidden" name="id" th:value="${id}">
<button type="submit" class="btn btn-default">提交</button>
</form>
</body>
</html>
注意:
● 文件上傳必須是post請求
● enctype必須為multipart/form-data
● 合同的id通過隱藏域傳遞
④ 在pom.xml文件中加入FastDFS客戶端的jar包依賴
<!--加入FastDFS的java客戶端依賴-->
<dependency>
<groupId>org.csource</groupId>
<artifactId>fastdfs-client-java</artifactId>
<version>1.27-SNAPSHOT</version>
</dependency>
⑤ 將FastDFS客戶端的配置文件fast_client.conf拷貝到resources目錄下
⑥ 將原來我們封裝的FastDFS類拷貝到fastdfs包下,修改其中的file_upload方法,定義一些參數
去掉主方法,新的fileUpload寫法如下:
/上傳文件的方法
public static String[] fileUpload(byte[] fileBytes,String fileExt){
String [] uploadArray = null;
try {
//1. 獲取StorageClient對象
StorageClient storageClient = getStorageClient();
//2.上傳文件 第一個參數:本地文件路徑 第二個參數:上傳文件的后綴 第三個參數:文件信息
uploadArray = storageClient.upload_file(fileBytes,fileExt,null);
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
} finally {
closeFastDFS();
}
return uploadArray;
}
⑦ 在CreditorController中添加處理上傳文件的方法
@PostMapping("/fastdfs/upload")
public @ResponseBody String upload(@RequestParam("id") Integer id, @RequestParam("fileName") MultipartFile file){
//原來文件上傳是將文件寫到本地或者遠程服務器的某個目錄下
//現在的文件上傳是將文件上傳到fastdfs文件服務器上
//1表示上傳失敗 0表示成功
int result = 1;
//abc.txt -->txt
String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf(".") + 1);
try {
String[] uploadArray = FastDFS.fileUpload(file.getBytes(),fileExt);
if(uploadArray != null && uploadArray.length ==2){
//文件上傳到fastDFS成功 ,將合同文件路徑更新到債權記錄中
CreditorInfo creditorInfo = new CreditorInfo();
creditorInfo.setId(id);
creditorInfo.setGroupname(uploadArray[0]);
creditorInfo.setRemotefilepath(uploadArray[1]);
int updateRow = creditorService.updateCreditorInfo(creditorInfo);
//數據庫更新成功
if(updateRow > 0){
result = 0;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return "<script>window.parent.uploadOK('"+result+"')</script>";
}
⑧ 在CreditorInfoService中添加updateCreditorInfo方法
/**
* 更新債權信息
* @param creditorInfo
* @return
*/
int updateCreditorInfo(CreditorInfo creditorInfo);
⑨ 在CreditorInfoServiceImpl中添加updateCreditorInfo方法實現
@Override
public int updateCreditorInfo(CreditorInfo creditorInfo) {
return creditorInfoMapper.updateByPrimaryKeySelective(creditorInfo);
}
⑩ 在upload.html做一個類似ajax的頁面不刷新效果
● 在upload.html頁面中加一個iframe
● upload.html頁面中的form中的target設置為iframe的name
● 在iframe的父頁面中,寫一個函數,處理上傳結果
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title>債權合同上傳</title>
<link rel="stylesheet" th:href="@{/css/bootstrap-3.3.7.min.css}">
<script th:src="@{/js/jquery-2.1.1.min.js}"></script>
<script th:src="@{/js/bootstrap-3.3.7.min.js}"></script>
</head>
<body>
<form th:action="@{/fastdfs/upload}" class="form-inline" role="form" method="post" target="uploadFrame" enctype="multipart/form-data">
<div class="form-group">
<label class="sr-only" for="fileName">文件輸入</label>
<input type="file" id="fileName" name="fileName">
</div>
<input type="hidden" id="id" name="id" th:value="${id}">
<button type="submit" class="btn btn-default">提交</button>
</form>
<iframe name="uploadFrame" style="display: none;"></iframe>
<script type="text/javascript" th:inline="javascript">
function uploadOK(result){
if(result == 0){
//文件上傳成功
alert("文件上傳成功");
var contextPath = [[${#request.getContextPath()}]];
window.location.href = contextPath + "/fastdfs/index";
}else{
alert("文件上傳失敗");
}
}
</script>
</body>
</html>
? 如果上傳文件超出了1M,需要在application.properties中配置SpringBoot上傳文件的最大限制
#SpringBoot上傳文件的最大限制
spring.servlet.multipart.max-file-size=10MB
注意:如果提示找不到tracker_server,看看是否編譯到target中
① 修改index.html頁面,下載加連接,并做判斷
<td>
<span th:if="${creditorInfo.getGroupname() ne null && creditorInfo.remotefilepath ne null}">
<a th:href="@{'/fastdfs/download?id=' + ${creditorInfo.id}}">下載</a>
刪除
</span>
<span th:unless="${creditorInfo.getGroupname() ne null && creditorInfo.remotefilepath ne null}">
<!--為哪個合同上傳,需要將合同的id傳遞過去-->
<a th:href="@{'/fastdfs/toUpload?id=' + ${creditorInfo.id}}">上傳</a>
</span>
</td>
② 在CreditorController中,完成下載的請求
● ResponseEntity通常用于返回文件流
● @ResponseBody可以直接返回Json結果,
● @ResponseEntity不僅可以返回json結果,還可以定義返回的HttpHeaders和HttpStatus
● ResponseEntity的優先級高于@ResponseBody。在不是ResponseEntity的情況下才去檢查有沒有@ResponseBody注解。如果響應類型是ResponseEntity可以不寫@ResponseBody注解,寫了也沒有關系。
@GetMapping("/fastdfs/download")
public ResponseEntity<byte[]> download(@RequestParam("id") Integer id){
//根據債權id獲取 債權對象
CreditorInfo creditorInfo = creditorInfoService.getCreditorInfoById(id);
String extName = creditorInfo.getRemotefilepath().substring(creditorInfo.getRemotefilepath().indexOf("."));
byte [] fileBytes = FastDFS.fileDownload(creditorInfo.getGroupname(),creditorInfo.getRemotefilepath());
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);//流類型
httpHeaders.setContentDispositionFormData("attachment",System.currentTimeMillis() + extName);
ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(fileBytes,httpHeaders, HttpStatus.OK);
return responseEntity;
}
③ 在CreditorService接口中添加getCreditorInfoById的方法
/**
* 根據合同id獲取債權信息
* @param id
* @return
*/
CreditorInfo getCreditorInfoById(Integer id);
④ 在CreditorServiceImpl中添加getCreditorInfoById方法的實現
@Override
public CreditorInfo getCreditorInfoById(Integer id) {
return creditorInfoMapper.selectByPrimaryKey(id);
}
⑤ 修改FastDFS類中fileDown方法的實現,傳遞參數
//下載文件的方法
public static byte[] fileDownload(String group,String remoteFile){
byte[] fileBytes = null;
try {
//1. 獲取StorageClient對象
StorageClient storageClient = getStorageClient();
//2.下載文件 返回0表示成功,其它均表示失敗
fileBytes = storageClient.download_file(group,remoteFile);
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
} finally {
closeFastDFS();
}
return fileBytes;
}
⑥ 瀏覽器訪問下載測試效果
① 在index.html頁面為刪除加超鏈接
<span th:if="${creditorInfo.getGroupname() ne null && creditorInfo.remotefilepath ne null}">
<a th:href="@{'/fastdfs/download?id=' + ${creditorInfo.id}}">下載</a>
<a th:href="@{'javascript:deleteFile('+ ${creditorInfo.id} +')'}">刪除</a>
</span>
② 在index.html頁面提供js方法,并發送ajax請求,對響應結果進行處理
<script type="text/javascript" th:inline="javascript">
function deleteFile(id){
//獲取項目的上下文根
var contextPath = [[${#request.getContextPath()}]];
$.ajax({
url:contextPath +"/fastdfs/fileDelete",
type:"post",
data:{
"id":id
},
success:function(responseMsg){
if(responseMsg==0){
alert("刪除成功");
window.location.reload();
}else{
alert("刪除失敗");
}
}
});
}
</script>
③ 在CreditorController中處理刪除請求
注意:刪除FastDFS和清除數據庫,所以我們將這些業務都放在service中進行事務的處理
@RequestMapping("/fastdfs/fileDelete")
public @ResponseBody String fileDelete(@RequestParam("id") Integer id){
int result = 1;
try {
result = creditorService.deleteContract(id);
} catch (Exception e) {
e.printStackTrace();
}
return String.valueOf(result);
}
④ 在CreditorService接口中加刪除合同的方法deleteContract
因為目前提供的方法,如果group和remoteFilePath為空就不更新,所以我們需要自己提供
/**
* 刪除合同
* @param id
* @return
*/
int deleteContract(Integer id);
⑤ 在CreditorServiceImpl類中對deleteContract方法進行實現
@Override
@Transactional //加上該注解控制事務
public int deleteContract(Integer id) {
// 1 刪除失敗;0 刪除成功
int result = 1;
//根據債權id獲取債權信息
CreditorInfo creditorInfo = creditorInfoMapper.selectByPrimaryKey(id);
/**
* 注意:事務控制的數據庫,所以我們先對數據庫進行更新,在操作FastDFS
* 如果操作FastDFS失敗了,那么對數據庫的操作回滾
*/
//更新數據庫債權表的合同路徑及組
int updateRow = creditorInfoMapper.updateConstractById(id);
if(updateRow > 0){
//如果數據庫更新成功,那么刪除FastDFS上的文件
int num = FastDFS.fileDelete(creditorInfo.getGroupname(),creditorInfo.getRemotefilepath());
if(num == 0){
//如果刪除成功,那么將整個操作結果設置為0,表示成功
result = 0;
}else{
//如果刪除FastDFS上的文件失敗,我們拋出一個運行異常,回滾事務
throw new RuntimeException("FastDFS文件刪除失敗");
}
}
return result;
}
⑥ 在CreditorMapper類中添加更新的方法
/**
* 根據債權的id,將組和合同路徑更新為null
* @param id
* @return
*/
int updateConstractById(Integer id);
⑦ 在CreditorMapper.xml中添加更新的方法
<update id="updateConstractById" parameterType="java.lang.Integer">
update creditor_info
set
groupName = NULL ,
remoteFilePath = NULL
where id = #{id,jdbcType=INTEGER}
</update>
⑧ 修改FastDFS類中的fileDelete方法,提供參數
//刪除文件的方法
public static int fileDelete(String group ,String remoteFile){
int num = 1;
try {
//1. 獲取StorageClient對象
StorageClient storageClient = getStorageClient();
//2.刪除文件 返回0表示成功,其它均表示失敗
num = storageClient.delete_file(group,remoteFile);
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
} finally {
closeFastDFS();
}
return num;
}
⑨ 在Application類上開啟事務支持
@SpringBootApplication
@EnableTransactionManagement
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
7. 功能實現-彈層組建layer的使用(簡單介紹)
官網:https://www.layui.com
2018開源軟件排行比較靠前