1.今日任務安排
? 學習自己的負責的模塊的相關知識,自己上網查詢或兩兩交流學習,主要學習數據庫相關、Java后端設計、WEB前端設計如CSS樣表語法、JS語法等。
? 開會確定每個人撰寫的前端和后端部分代碼以及數據庫部分代碼
? 開始撰寫具體的代碼
2.遇到的困難
由于有關于web前端后端的知識是上個學期web選修課上學習的,因此一開始對于頁面設計以及后端請求的編寫非常的生疏,有很多相關的知識都已經遺忘,于是在菜鳥網站上大家進行了基本操作的復習,在回憶起上學期學習的知識以后,開始撰寫頁面設計和后端請求的代碼。
3.今日成果
? ArticleController.java
package cn.edu.nuc.article.controller;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import cn.edu.nuc.article.util.SM4Utils;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import cn.edu.nuc.article.dto.TreeDto;
import cn.edu.nuc.article.entity.Article;
import cn.edu.nuc.article.entity.Attachment;
import cn.edu.nuc.article.entity.AuditMessage;
import cn.edu.nuc.article.entity.Log;
import cn.edu.nuc.article.entity.User;
import cn.edu.nuc.article.service.ArticleService;
import cn.edu.nuc.article.service.AttachmentService;
import cn.edu.nuc.article.service.AuditMessageService;
import cn.edu.nuc.article.service.FileService;
import cn.edu.nuc.article.service.LogService;
import cn.edu.nuc.article.service.ReceiveService;
import cn.edu.nuc.article.service.UserService;
import cn.edu.nuc.article.util.IpUtil;
/**
* 公文Controller
*
*/
@Controller
@RequestMapping("/article")
public class ArticleController {
/**
* 公文Service
*/
@Autowired
private ArticleService articleService;
/**
* 用戶Service
*/
@Autowired
private UserService userService;
/**
* 文件服務
*/
@Autowired
private FileService fileService;
/**
* 公文接收Service
*/
@Autowired
private ReceiveService receiveService;
/**
* 附件Service
*/
@Autowired
private AttachmentService attachmentService;
/**
* 公文審核信息Service
*/
@Autowired
private AuditMessageService auditMessageService;
/**
* 日志Service
*/
@Autowired
private LogService logService;
/**
* Activiti運行時Service,用于啟動流程
*/
@Autowired
private RuntimeService runtimeService;
/**
* Activiti任務Service,查詢待辦任務和完成任務
*/
@Autowired
private TaskService taskService;
/**
* 公文修改(撰稿)
* @return
*/
@RequestMapping("/modifyArticle")
@Transactional
public String modifyArticle(Map<String, Object> map, HttpSession session ,
String title, Integer articleId, Integer[] received, Integer auditor,
String taskId,
@RequestParam(name= "doc", required = false) MultipartFile doc,
@RequestParam(name= "attachment", required = false) MultipartFile[] attachment) {
try {
//1.首先檢查必填項是否都填寫正確
if (!validateForm(map, articleId, title, received, auditor, doc)) {
return "forward:/article/toModify";
}
//2.設置公文相關參數并新增公文
Article article = new Article();
article.setArticleid(articleId);
article.setArticlestate(0); //0表示審核中
article.setTitle(title);
//撰稿人、審稿人、發布時間在公文撰稿時已經設置過,不需要也不能改
//判斷操作結果是否成功
if (!articleService.modifyArticle(article)) {
map.put("msg", "系統出現錯誤,在修改公文信息時操作失敗!");
map.put("result", false);
return "forward:/article/toModify";
}
//拿到修改后的公文信息
User user = (User) session.getAttribute("user");
article = articleService.getArticleById(articleId, user.getUserid());
//3 刪除舊的接收關系,再添加信息
//3.1 刪除舊的接收關系
if (receiveService.deleteReceive(articleId)) {
//3.2 添加新的接收人信息
for (Integer receiverId : received) {
if (!receiveService.addReceive(articleId, receiverId)) {
map.put("msg", "系統出現錯誤,在修改公文接收人信息時操作失敗!");
map.put("result", false);
return "forward:/article/toModify";
}
}
} else {
map.put("msg", "系統出現錯誤,在修改公文接收人信息時操作失敗!");
map.put("result", false);
return "forward:/article/toModify";
}
//4. 看一下公文原文是否需要更新,如果需要則更新之
if (doc != null && doc.getSize() != 0) {
//4.1 刪掉舊的公文原文信息
Attachment target = null;
for (Attachment attachment2 : article.getAttachments()) {
if (attachment2.getAttachtype() == 0) { //正文
target = attachment2;
}
}
boolean result = attachmentService.deleteAttachment(target.getAttachmentid());
if (result) {
//4.2 調用FileService,使用JackRabbit保存新的公文電子文檔
String fileId = fileService.save(doc.getInputStream());
//4.3 拼裝出公文原文的附件信息
Attachment articleDocument = new Attachment();
articleDocument.setArticleId(article.getArticleid());
articleDocument.setAttachtype(0); //0表示正文
articleDocument.setFilename(doc.getOriginalFilename());
articleDocument.setMimetype(doc.getContentType());
articleDocument.setUploadtime(new Date());
articleDocument.setFilesize(doc.getSize());
articleDocument.setFileid(fileId); //JackRabbit返回的FileId
//4.4 添加信息到附件表
if (!attachmentService.addAttachment(articleDocument)) {
map.put("msg", "系統出現錯誤,在添加公文附件時操作失敗!");
map.put("result", false);
return "forward:/article/toModify";
}
} else {
map.put("msg", "系統出現錯誤,在刪除公文舊附件時操作失敗!");
map.put("result", false);
return "forward:/article/toModify";
}
}
//5.如果用戶上傳了附件,就要做對應更新
if (attachment != null && attachment.length != 0 && attachment[0].getSize() != 0) {
//5.1 刪掉公文舊附件
for (Attachment attachment2 : article.getAttachments()) {
if (attachment2.getAttachtype() != 0) { //附件
attachmentService.deleteAttachment(attachment2.getAttachmentid());
}
}
//5.2 上傳新附件
for (MultipartFile attachFile : attachment) {
//5.2.1 調用FileService,使用JackRabbit保存公文附件
String attfileId = fileService.save(attachFile.getInputStream());
//5.2.2 拼裝附件信息
Attachment attch = new Attachment();
attch.setArticleId(article.getArticleid());
attch.setAttachtype(1); //1表示附件
attch.setFileid(attfileId);
attch.setFilename(attachFile.getOriginalFilename());
attch.setFilesize(attachFile.getSize());
attch.setMimetype(attachFile.getContentType());
attch.setUploadtime(new Date());
//5.2.3 添加信息到附件表
if (!attachmentService.addAttachment(attch)) {
map.put("msg", "系統出現錯誤,在修改公文附件時操作失敗!");
map.put("result", false);
return "forward:/article/toModify";
}
}
}
//6.完成公文修改的待辦任務,使其轉向公文審核任務
//6.1 完成選擇,使其轉向修改公文任務
Map<String, Object> variables = new HashMap<>();
variables.put("decision", true);
taskService.complete(taskId, variables);
//6.2 根據流程實例和辦理人查詢待辦,得到修改公文任務的TaskId,然后完成該任務
Task task = taskService.createTaskQuery()
.taskAssignee(user.getUserid().toString())
.processInstanceId(article.getProcessinstanceId())
.singleResult();
taskService.complete(task.getId());
//7.如果以上操作都沒有問題,那就是成功了
map.put("msg", "公文[" + article.getTitle() + "]上傳成功,請耐心等待審核!");
map.put("result", true);
//返回等待審核結果界面
return "forward:/article/toAduitResult";
} catch (Exception e) {
System.out.println("公文修改出錯!");
e.printStackTrace();
map.put("msg", "系統出現嚴重錯誤,公文修改操作失敗!");
map.put("result", false);
return "forward:/article/toModfiy";
}
}
/**
* 進入公文修改界面
* @return
* @throws Exception
*/
@RequestMapping("/toModfiy")
public String toModify(HttpSession session, Map<String, Object> map,
Integer articleId, String taskId) throws Exception {
//加載出該用戶所在機構所有審稿人姓名
//1 從Session中取出User
User user = (User) session.getAttribute("user");
//2 通過用戶得到其所在機構的id
Integer instid = user.getInstId();
//3 得到該機構所有未被禁用的審核人員的信息
List<User> auditors = userService.findValidAuditor(instid);
//4 得到公文信息
Article article = articleService.getArticleById(articleId, user.getUserid());
//5 保存為備選項
map.put("auditors", auditors);
map.put("article", article);
map.put("taskId", taskId);
return "article/articlemodify";
}
/**
* 通過Ajax方式獲得聯系人樹(修改)
* @return
* @throws Exception
*/
@ResponseBody
@RequestMapping("/getTreeModify")
public List<TreeDto> getTreeModify(HttpSession session, Integer articleId)
throws Exception {
User user = (User) session.getAttribute("user");
List<TreeDto> dtos = new ArrayList<>();
dtos.add(articleService.getTreeDTOJSON(articleId, user.getUserid()));
return dtos;
}
/**
* 用戶選擇刪除公文
* @param map
* @return
*/
@RequestMapping("/deleteArticle")
public String deleteArticle(Map<String, Object> map, Integer articleId, String taskId) {
//設置公文狀態為被刪除
Article article = new Article();
article.setArticleid(articleId);
article.setArticlestate(4);
if (articleService.modifyArticle(article)) {
Map<String, Object> variables = new HashMap<>();
variables.put("decision", false);
taskService.complete(taskId, variables);
map.put("msg", "刪除公文成功");
map.put("result", true);
} else {
map.put("msg", "刪除公文失敗");
map.put("result", false);
}
return "forward:/article/toAduitResult";
}
/**
* 按id加載公文接收信息
* @return
*/
@RequestMapping("/findByIdHistory")
public String findByIdHistory(Map<String, Object> map, HttpSession session,
HttpServletRequest request, Integer articleId) {
//1.從Session中獲得User,取得其UserId
User user = (User) session.getAttribute("user");
Integer userId = user.getUserid();
//2.向日志表插入一條日志記錄
Log log = new Log();
log.setBussinessId(articleId);
log.setIpaddress(IpUtil.getRequestRealIp(request)); //獲取ip地址
log.setOperatorId(userId);
log.setOptname("查看公文");
log.setOpttime(new Date());
logService.addLog(log);
//3.檢查訪問權限
if (articleService.isArticleAvaliable(articleId, userId)) {
Article article = articleService.getArticleById(articleId, userId);
//4.保存查詢結果
map.put("article", article);
return "article/articleDetail";
} else {
map.put("msg", "您沒有查看公文的權限!");
map.put("result", false);
return "forward:/article/getMyHistoryList";
}
}
/**
* 查詢接收公文信息
* @param map
* @param session
* @param keyword
* @return
*/
@RequestMapping("/getMyHistoryList")
public String getMyHistoryList(Map<String, Object> map, HttpSession session,
@RequestParam(value="keyword", required=false) String keyword) {
//找出當前登錄用戶
User user = (User) session.getAttribute("user");
//設置查詢條件
Article article = new Article();
article.setUserId(user.getUserid());
if (StringUtils.hasText(keyword)) { //用戶指定了查詢關鍵字
article.setTitle(keyword);
}
List<Article> articles = articleService.getMyArticleList(article);
//保存結果集帶到頁面顯示
map.put("articles", articles);
//保存模糊查詢條件以便回顯
map.put("keyword", keyword);
return "article/articleHistoryManage";
}
/**
* 按id加載公文接收信息
* @return
*/
@RequestMapping("/findByIdReceive")
public String findByIdReceive(Map<String, Object> map, HttpSession session,
HttpServletRequest request, Integer articleId) {
//1.從Session中獲得User,取得其UserId
User user = (User) session.getAttribute("user");
Integer userId = user.getUserid();
//2.向日志表插入一條日志記錄
Log log = new Log();
log.setBussinessId(articleId);
log.setIpaddress(IpUtil.getRequestRealIp(request)); //獲取ip地址
log.setOperatorId(userId);
log.setOptname("查看公文");
log.setOpttime(new Date());
logService.addLog(log);
//3.檢查訪問權限
if (articleService.isArticleAvaliable(articleId, userId)) {
Article article = articleService.getArticleById(articleId, userId);
//4.保存查詢結果
map.put("article", article);
return "article/articleDetail";
} else {
map.put("msg", "您沒有查看公文的權限!");
map.put("result", false);
return "forward:/article/getMyReceiveList";
}
}
/**
* 查詢接收公文信息
* @param map
* @param session
* @param keyword
* @return
*/
@RequestMapping("/getMyReceiveList")
public String getMyReceiveList(Map<String, Object> map, HttpSession session,
@RequestParam(value="keyword", required=false) String keyword) {
//找出當前登錄用戶
User user = (User) session.getAttribute("user");
//設置查詢條件
Article article = new Article();
article.setArticlestate(3);
article.setUserId(user.getUserid());
if (StringUtils.hasText(keyword)) { //用戶指定了查詢關鍵字
article.setTitle(keyword);
}
List<Article> articles = articleService.getMyArticles(article);
//保存結果集帶到頁面顯示
map.put("articles", articles);
//保存模糊查詢條件以便回顯
map.put("keyword", keyword);
return "article/articleReceiveManage";
}
/**
* 提交公文審核結果
* @param map
* @param taskId
* @param result
* @param articleId
* @param auditmessage
* @return
*/
@RequestMapping("/submitAuditResult")
public String submitAuditResult(Map<String, Object> map, String taskId,
Integer result, Integer articleId, String auditmessage){
AuditMessage auditMessage = new AuditMessage();
auditMessage.setAuditdate(new Date());
auditMessage.setAuditmessage(auditmessage);
auditMessage.setAuditresult(result);
auditMessage.setArticleId(articleId);
//先添加審核信息
if (auditMessageService.addAuditMessage(auditMessage)) {
Map<String, Object> variables = new HashMap<>();
if (result == 1) { //審核通過
variables.put("auditresult", true);
Article article = new Article();
article.setArticleid(articleId);
article.setArticlestate(3); //3表示審核通過且發布
articleService.modifyArticle(article); //更新數據庫字段
} else {
variables.put("auditresult", false);
Article article = new Article();
article.setArticleid(articleId);
article.setArticlestate(2); //2表示審核駁回
articleService.modifyArticle(article); //更新數據庫字段
}
//使用流程變量完成待辦任務
taskService.complete(taskId, variables);
map.put("msg", "提交審核結果成功!");
map.put("result", true);
} else {
map.put("msg", "提交審核結果失敗!");
map.put("result", false);
}
return "redirect:/article/toAduit";
}
/**
* 下載公文或附件
* @param session
* @param filename
* @param fileId
* @return
* @throws Exception
*/
@RequestMapping("/download")
public ResponseEntity<byte[]> downloadArticle(HttpSession session,
HttpServletRequest request, HttpServletResponse httpServletResponse,
Integer attachmentid, String fileId) throws Exception {
byte [] body = null;
Attachment attachment = new Attachment();
attachment.setAttachmentid(attachmentid);
attachment = attachmentService.findByKeyword(attachment).get(0);
User user = (User) session.getAttribute("user");
boolean result = articleService.isArticleAvaliable(
attachment.getArticleId(), user.getUserid());
if (result) {
//如果下載的是公文原文而不是附件,則向日志表插入一條日志記錄
if (attachment.getAttachtype() == 0) {
Log log = new Log();
log.setBussinessId(attachment.getArticleId());
log.setIpaddress(IpUtil.getRequestRealIp(request)); //獲取ip地址
log.setOperatorId(user.getUserid());
log.setOptname("下載公文");
log.setOpttime(new Date());
logService.addLog(log);
}
//通過JackRabbit找到文件,獲得輸入流
InputStream in = fileService.getByFileId(fileId);
body = new byte[in.available()];
in.read(body);
// TODO 需要對文件進行解密
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename="
+ new String(attachment.getFilename().getBytes(), "ISO-8859-1"));
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> response =
new ResponseEntity<byte[]>(body, headers, statusCode);
return response;
}
return null;
}
/**
* 按id加載公文信息
* @return
*/
@RequestMapping("/toAuditPage")
public String toAuditPage(Map<String, Object> map,
HttpSession session, Integer articleId) {
//1.從Session中獲得User,取得其UserId
User user = (User) session.getAttribute("user");
Integer userId = user.getUserid();
//2. 讀取當前用戶的待辦任務,包括直接分配給當前人或已經簽收的任務
List<Task> doingTask = taskService.createTaskQuery()
.taskAssignee(user.getUserid().toString()).list();
//2.檢查訪問權限
if (articleService.isArticleAvaliable(articleId, userId)) {
//3.查詢公文信息
Article article = articleService.getArticleById(articleId, userId);
//4.根據公文的流程實例id找到當前任務
Task task = null;
for (Task task1 : doingTask) {
if (article.getProcessinstanceId().equals(task1.getProcessInstanceId())) {
task = task1;
}
}
//3.保存查詢結果
map.put("article", article);
map.put("task", task);
return "article/articleAuditDetail";
} else {
map.put("msg", "您沒有查看公文的權限!");
map.put("result", false);
return "forward:/article/toAduit";
}
}
/**
* 按id加載公文審核結果信息
* @return
*/
@RequestMapping("/findById")
public String findById(Map<String, Object> map, HttpSession session,
HttpServletRequest request, Integer articleId) {
//1.從Session中獲得User,取得其UserId
User user = (User) session.getAttribute("user");
Integer userId = user.getUserid();
//2.檢查訪問權限
if (articleService.isArticleAvaliable(articleId, userId)) {
//3.向日志表插入一條日志記錄
Log log = new Log();
log.setBussinessId(articleId);
log.setIpaddress(IpUtil.getRequestRealIp(request)); //獲取ip地址
log.setOperatorId(userId);
log.setOptname("查看公文");
log.setOpttime(new Date());
logService.addLog(log);
Article article = articleService.getArticleById(articleId, userId);
//4.保存查詢結果
map.put("article", article);
return "article/articleDetail";
} else {
map.put("msg", "您沒有查看公文的權限!");
map.put("result", false);
return "forward:/article/toAduitResult";
}
}
/**
* 進入審核界面
* @param map
* @param pageNo
* @param pageCount
* @param keyword
* @return
*/
@RequestMapping("/toAduit")
public String toAduit(Map<String, Object> map, HttpSession session,
@RequestParam(value="keyword", required=false) String keyword) {
// 查詢得到結果集
List<Article> articles;
User user = (User) session.getAttribute("user");
//讀取當前用戶的待辦任務,包括直接分配給當前人或已經簽收的任務
List<Task> doingTask = taskService.createTaskQuery()
.taskAssignee(user.getUserid().toString()).list();
if (doingTask != null && doingTask.size() != 0) { //有該用戶的待辦任務
if (StringUtils.hasText(keyword)) { //用戶指定了查詢關鍵字
articles = articleService.getByProcessInstances(doingTask, keyword, Arrays.asList(0));
} else { //用戶沒指定查詢關鍵字
articles = articleService.getByProcessInstances(doingTask, null, Arrays.asList(0));
}
} else { //沒有待辦任務
articles = new ArrayList<>();
}
//保存結果集帶到頁面顯示
map.put("articles", articles);
map.put("tasks", doingTask);
//保存模糊查詢條件以便回顯
map.put("keyword", keyword);
return "article/articleAuditManage";
}
/**
* 進入審核結果
* @param map
* @param pageNo
* @param pageCount
* @param keyword
* @return
*/
@RequestMapping("/toAduitResult")
public String toAduitResult(Map<String, Object> map, HttpSession session,
@RequestParam(value="keyword", required=false) String keyword) {
// 查詢得到結果集
List<Article> articles;
User user = (User) session.getAttribute("user");
//讀取當前用戶的待辦任務,包括直接分配給當前人或已經簽收的任務
List<Task> doingTask = taskService.createTaskQuery()
.taskAssignee(user.getUserid().toString()).list();
if (doingTask != null && doingTask.size() != 0) { //有該用戶的待辦任務
if (StringUtils.hasText(keyword)) { //用戶指定了查詢關鍵字
articles = articleService.getByProcessInstances(doingTask, keyword, Arrays.asList(1, 2));
} else { //用戶沒指定查詢關鍵字
articles = articleService.getByProcessInstances(doingTask, null, Arrays.asList(1, 2));
}
} else { //沒有待辦任務
articles = new ArrayList<>();
}
//為每一篇公文加入對應的Task
for (Task task : doingTask) {
for (Article article : articles) {
if (task.getProcessInstanceId().equals(article.getProcessinstanceId())) {
article.setTask(task);
}
}
}
//查詢出正在審核中的公文
Article article = new Article();
article.setTitle(keyword);
article.setUserId(user.getUserid());
List<Article> auditing = articleService.getMyAuditList(article);
articles.addAll(auditing); //合并兩個集合
//保存結果集帶到頁面顯示
map.put("articles", articles);
map.put("tasks", doingTask);
//保存模糊查詢條件以便回顯
map.put("keyword", keyword);
return "article/articleAuditResultManage";
}
/**
* 公文上傳(撰稿)
* @return
*/
@RequestMapping("/addArticle")
@Transactional
public String addArticle(Map<String, Object> map, HttpSession session ,
String title,
Integer[] received,
Integer auditor,
MultipartFile doc,
String docBase64,
String attachmentBase64,
@RequestParam(name= "attachment", required = false) MultipartFile[] attachment) {
try {
//1.首先檢查必填項是否都填寫正確
if (!validateForm(map, null, title, received, auditor, doc)) {
return "forward:/article/toAdd";
}
//2.設置公文相關參數并新增公文
Article article = new Article();
article.setArticlestate(0); //0表示審核中
article.setTitle(title);
//撰稿人就是當前用戶
User user = (User)session.getAttribute("user");
article.setCopywriterId(user.getUserid());
article.setInstId(user.getInstId());
article.setAuditorId(auditor);
article.setPublishtime(new Date());
//判斷操作結果是否成功
if (!articleService.addArticle(article)) {
map.put("msg", "系統出現錯誤,在添加公文信息時操作失敗!");
map.put("result", false);
return "forward:/article/toAdd";
}
//3.啟動Activiti工作流流程,拿到流程實例id
//3.1 設置流程變量,指定審核人(為防止用戶姓名重復,使用用戶id)
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("auditorId", auditor); //指定公文審核的辦理人Id
variables.put("copywriterId", user.getUserid()); //指定撰稿人Id
//3.2 按流程實例id啟動流程
// ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(
// "articleProcess", article.getArticleid().toString() , variables);
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(
"articleProcess", article.getArticleid().toString() , variables);
//3.3 得到流程實例id
String procInstanceKey = processInstance.getId();
//3.4 更新公文信息,設置流程id
article.setProcessinstanceId(procInstanceKey);
if (!articleService.modifyArticle(article)) {
map.put("msg", "系統出現錯誤,在添加公文信息時操作失敗!");
map.put("result", false);
return "forward:/article/toAdd";
}
//4 利用公文id繼續去添加其他信息
//4.1 添加接收關系
for (Integer receiverId : received) {
if (!receiveService.addReceive(article.getArticleid(), receiverId)) {
map.put("msg", "系統出現錯誤,在添加公文接收信息時操作失敗!");
map.put("result", false);
return "forward:/article/toAdd";
}
}
SM4Utils sm4 = new SM4Utils();
String decryptStr = sm4.decryptData_ECB(docBase64);
// 解碼Base64字符串為字節數組
byte[] decodedBytes = Base64.getDecoder().decode(decryptStr);
ByteArrayInputStream docBase = new ByteArrayInputStream(decodedBytes);
//4.2 調用FileService,使用JackRabbit保存公文電子文檔
String fileId = fileService.save(docBase);
//4.3 拼裝出公文原文的附件信息
Attachment articleDocument = new Attachment();
articleDocument.setArticleId(article.getArticleid());
articleDocument.setAttachtype(0); //0表示正文
articleDocument.setFilename(doc.getOriginalFilename());
articleDocument.setMimetype(doc.getContentType());
articleDocument.setUploadtime(new Date());
articleDocument.setFilesize(doc.getSize());
articleDocument.setFileid(fileId); //JackRabbit返回的FileId
//4.4 添加信息到附件表
if (!attachmentService.addAttachment(articleDocument)) {
map.put("msg", "系統出現錯誤,在添加公文附件時操作失敗!");
map.put("result", false);
return "forward:/article/toAdd";
}
//5.如果用戶上傳了附件,就要把附件也保存下來
for (MultipartFile attachFile : attachment) {
//5.1 調用FileService,使用JackRabbit保存公文附件
decryptStr = sm4.decryptData_ECB(attachmentBase64);
// docBase = new ByteArrayInputStream(decryptStr.getBytes());
// String attfileId = fileService.save(docBase);
String attfileId = fileService.save(attachFile.getInputStream());
//5.2 拼裝附件信息
Attachment attch = new Attachment();
attch.setArticleId(article.getArticleid());
attch.setAttachtype(1); //1表示附件
attch.setFileid(attfileId);
attch.setFilename(attachFile.getOriginalFilename());
attch.setFilesize(attachFile.getSize());
attch.setMimetype(attachFile.getContentType());
attch.setUploadtime(new Date());
//5.3 添加信息到附件表
if (!attachmentService.addAttachment(attch)) {
map.put("msg", "系統出現錯誤,在添加公文附件時操作失敗!");
map.put("result", false);
return "forward:/article/toAdd";
}
}
//6.如果以上操作都沒有問題,那就是成功了
map.put("msg", "公文[" + article.getTitle() + "]上傳成功,請耐心等待審核!");
map.put("result", true);
//返回等待審核結果界面
return "forward:/article/toAduitResult";
} catch (Exception e) {
System.out.println("公文撰稿出錯!");
e.printStackTrace();
map.put("msg", "系統出現嚴重錯誤,公文撰稿操作失敗!");
map.put("result", false);
return "forward:/article/toAdd";
}
}
/**
* 檢查公文撰稿表單是否填寫正確
* @param map
* @param title
* @param received
* @param auditor
* @param doc
* @return
*/
private boolean validateForm(Map<String, Object> map, Integer articleid,
String title, Integer[] received, Integer auditor, MultipartFile doc) {
//1.1檢查公文標題是否符合規定格式
if (!StringUtils.hasText(title)
|| !Pattern.matches("^\\S{2,150}$", title)) {
map.put("msg", "您填寫的公文標題不合法,上傳失敗!公文標題不能為空,并且長度為2~150。");
map.put("result", false);
return false;
}
//1.2 檢查接收人id是否填寫
if (received == null || received.length == 0) {
map.put("msg", "您還沒有選擇接收人,上傳失敗!");
map.put("result", false);
return false;
}
//1.3 檢查審核人是否填寫
if (articleid == null && auditor == null) {
map.put("msg", "您還沒有選擇審核人,上傳失敗!");
map.put("result", false);
return false;
}
//1.4 檢查公文電子文檔是否上傳
// if (articleid == null && doc == null) {
// map.put("msg", "您還沒有上傳公文電子文檔,上傳失敗!");
// map.put("result", false);
// return false;
// }
//1.5 檢查公文名稱是否重復,如果重復則不允許其通過
if (!articleService.validateTitle(title, articleid)) {
map.put("msg", "您填寫的公文標題與已有標題重復,上傳失敗!");
map.put("result", false);
return false;
}
return true;
}
/**
* 進入公文撰稿界面
* @return
* @throws Exception
*/
@RequestMapping("/toAdd")
public String toAdd(HttpSession session, Map<String, Object> map) throws Exception {
//加載出該用戶所在機構所有審稿人姓名
//1 從Session中取出User
User user = (User) session.getAttribute("user");
//2 通過用戶得到其所在機構的id
Integer instid = user.getInstId();
//3 得到該機構所有未被禁用的審核人員的信息
List<User> auditors = userService.findValidAuditor(instid);
//4 保存為備選項
map.put("auditors", auditors);
return "article/articleupload";
}
/**
* 通過Ajax方式獲得聯系人樹
* @return
* @throws Exception
*/
@ResponseBody
@RequestMapping("/getTree")
public List<TreeDto> getTree() throws Exception {
List<TreeDto> dtos = new ArrayList<>();
dtos.add(articleService.getTreeDTOJSON(null, null));
return dtos;
}
}
? FunctionController.java
package cn.edu.nuc.article.controller;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import cn.edu.nuc.article.entity.Function;
import cn.edu.nuc.article.service.FunctionService;
/**
* 功能Controller
*
*/
@Controller
@RequestMapping("/fun")
public class FunctionController {
/**
* 功能業務邏輯
*/
@Autowired
private FunctionService functionService;
/**
* 分頁+模糊查詢
* @param pageNo 當前頁
* @param pageCount 每頁記錄數
* @param function 待查參數
* @return
*/
@RequestMapping("/funs")
public String findByKeyword(Map<String, Object> map,
@RequestParam(value="pageNo", defaultValue="1", required=false) Integer pageNo,
@RequestParam(value="pageCount", defaultValue="10", required=false) Integer pageCount,
@RequestParam(value="keyword", required=false) String keyword) {
// 引入PageHelper分頁插件
// 在查詢之前只需要調用,傳入頁碼,以及每頁的大小
PageMethod.startPage(pageNo, pageCount);
// 分頁查詢得到結果集
List<Function> functions;
if (StringUtils.hasText(keyword)) {
Function function = new Function();
function.setFunname(keyword);
functions = functionService.getFunctionList(function);
} else {
functions = functionService.getFunctionList(null);
}
// 使用pageInfo包裝查詢后的結果,只需要將pageInfo交給頁面就行了。
// 封裝了詳細的分頁信息,包括有我們查詢出來的數據,傳入連續顯示的頁數
PageInfo<Function> page = new PageInfo<Function>(functions, 5);
//保存結果集帶到頁面顯示
map.put("page", page);
map.put("pageNo", pageNo);
map.put("pageCount", pageCount);
//保存模糊查詢條件以便回顯
map.put("keyword", keyword);
return "function/functionManage";
}
/**
* 跳到添加界面
* @return
*/
@RequestMapping("/toAdd")
public String toAdd(Map<String, Object> map) {
//取出所有的頂級功能和父功能,保存備選項供顯示
map.put("functionList", functionService.getTopFunctions());
return "function/functionadd";
}
/**
* 添加功能
* @return
*/
@RequestMapping("/addFunction")
public String addFunction(Map<String, Object> map, @Valid Function function, BindingResult bindingResult) {
//檢查校驗是否出錯
if(bindingResult.hasErrors()){
List<ObjectError> list = bindingResult.getAllErrors();
ObjectError oe = list.get(0);
//校驗失敗信息
map.put("result", false);
map.put("msg", oe.getDefaultMessage() + "添加功能[" + function.getFunname() + "]失敗!");
} else {
//功能名稱查重
boolean hasSame = functionService.hasSameFunction(null, function.getFunname());
if (!hasSame) { //功能名稱不重復
//保存功能信息,拿到添加操作的結果
boolean result = functionService.addFunction(function);
map.put("result", result);
//根據操作結果生成提示信息
if (result) { //添加成功且無重復
map.put("msg", "添加功能[" + function.getFunname() + "]成功!");
} else {
map.put("msg", "添加功能[" + function.getFunname() + "]失敗!");
}
} else {
map.put("result", false);
map.put("msg", "功能名稱[" + function.getFunname() + "]重復,添加功能失敗!");
}
}
return "forward:/fun/funs";
}
/**
* 跳到添加界面
* @return
*/
@RequestMapping("/toModify")
public String toModify(Map<String, Object> map, Integer funid) {
//取出所有的頂級功能和父功能,保存備選項供顯示
map.put("functionList", functionService.getTopFunctions());
//取出待修改功能信息
map.put("function", functionService.getFunctionById(funid));
return "function/functionmodify";
}
/**
* 修改功能
* @return
*/
@RequestMapping("/modifyFunction")
public String modifyFunction(Map<String, Object> map, @Valid Function function, BindingResult bindingResult) {
//檢查校驗是否出錯
if(bindingResult.hasErrors()){
List<ObjectError> list = bindingResult.getAllErrors();
ObjectError oe = list.get(0);
//校驗失敗信息
map.put("result", false);
map.put("msg", oe.getDefaultMessage() + "修改功能[" + function.getFunname() + "]失敗!");
} else {
//功能名稱查重
boolean hasSame = functionService.hasSameFunction(function.getFunid(), function.getFunname());
if (!hasSame) { //功能名稱不重復
//保存功能信息,拿到添加操作的結果
boolean result = functionService.modifyFunction(function);
map.put("result", result);
//根據操作結果生成提示信息
if (result) { //添加成功且無重復
map.put("msg", "修改功能[" + function.getFunname() + "]成功!");
} else {
map.put("msg", "修改功能[" + function.getFunname() + "]失敗!");
}
} else {
map.put("result", false);
map.put("msg", "功能名稱[" + function.getFunname() + "]重復,修改功能失敗!");
}
}
return "forward:/fun/funs";
}
/**
* 禁用
* @return
*/
@RequestMapping("/disable")
public String disableFunction(Map<String, Object> map, Integer funid) {
//保存功能信息,拿到刪除操作的結果
Function function = functionService.getFunctionById(funid);
function.setFunstate(0); //設為禁用
boolean result = functionService.modifyFunction(function);
map.put("result", result);
//根據操作結果生成提示信息
if (result) { //添加成功且無重復
map.put("msg", "禁用功能[" + function.getFunname() + "]成功!");
} else {
map.put("msg", "禁用功能[" + function.getFunname() + "]失敗!");
}
return "forward:/fun/funs";
}
/**
* 啟用
* @return
*/
@RequestMapping("/enable")
public String enableFunction(Map<String, Object> map, Integer funid) {
//保存功能信息,拿到刪除操作的結果
Function function = functionService.getFunctionById(funid);
function.setFunstate(1); //設為禁用
boolean result = functionService.modifyFunction(function);
map.put("result", result);
//根據操作結果生成提示信息
if (result) { //添加成功且無重復
map.put("msg", "啟用功能[" + function.getFunname() + "]成功!");
} else {
map.put("msg", "啟用功能[" + function.getFunname() + "]失敗!");
}
return "forward:/fun/funs";
}
}
? InstitutionController.java
package cn.edu.nuc.article.controller;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import cn.edu.nuc.article.entity.Institution;
import cn.edu.nuc.article.service.InstitutionService;
/**
* 機構Controller
*
*/
@Controller
@RequestMapping("/institution")
public class InstitutionController {
/**
* 機構Service
*/
@Autowired
private InstitutionService institutionService;
/**
* 進入合并界面
* @return
*/
@RequestMapping("/toMerge")
public String toMerge(Map<String, Object> map) {
//1.找出所有下面沒有用戶的機構
List<Institution> noUserInstitutions = institutionService.selectInstitutionNoUserUnder();
//2.找出所有下面有用戶并且沒有被禁用的機構
List<Institution> validInstitution = institutionService.selectInstitutionHasUserUnderAndValid();
//3.保存查詢結果
map.put("noUserInstitutions", noUserInstitutions);
map.put("validInstitution", validInstitution);
return "institution/instutionMerge";
}
/**
* 機構合并
* @param map
* @param instid1
* @param instid2
* @return
*/
@RequestMapping("/merge")
public String merge(Map<String, Object> map, Integer[] instid1, Integer instid2) {
boolean result = false;
try {
result = institutionService.merge(instid1, instid2);
} catch (Exception e) {
System.out.println("合并過程中出錯!");
e.printStackTrace();
}
//判斷操作是否成功
if (result) {
map.put("result", true);
map.put("msg", "合并組織機構成功!");
} else {
map.put("result", true);
map.put("msg", "合并組織機構出錯,操作失敗!");
}
return "forward:/institution/institutions";
}
/**
* 進入添加界面
* @return
*/
@RequestMapping("/toModify")
public String toModify(Map<String, Object> map, Integer instid) {
map.put("institution", institutionService.findById(instid));
return "institution/institutionmodify";
}
/**
* 執行修改操作
* @param map
* @param institution
* @param bindingResult
* @return
*/
@RequestMapping("/modify")
public String modify(Map<String, Object> map, @Valid Institution institution, BindingResult bindingResult) {
//檢查校驗是否出錯
if(bindingResult.hasErrors()){
List<ObjectError> list = bindingResult.getAllErrors();
ObjectError oe = list.get(0);
//校驗失敗信息
map.put("result", false);
map.put("msg", oe.getDefaultMessage() + "修改組織機構[" + institution.getInstname() + "]失敗!");
} else {
//功能名稱查重
boolean hasSame = institutionService.hasSameInstitution(
institution.getInstid(), institution.getInstname());
if (!hasSame) { //功能名稱不重復
//保存功能信息,拿到添加操作的結果
boolean result = institutionService.updateInstitution(institution);
map.put("result", result);
//根據操作結果生成提示信息
if (result) { //添加成功且無重復
map.put("msg", "修改組織機構[" + institution.getInstname() + "]成功!");
} else {
map.put("msg", "修改組織機構[" + institution.getInstname() + "]失敗!");
}
} else {
map.put("result", false);
map.put("msg", "組織機構名稱[" + institution.getInstname() + "]重復,修改組織機構失敗!");
}
}
return "forward:/institution/institutions";
}
/**
* 進入添加界面
* @return
*/
@RequestMapping("/toAdd")
public String toAdd() {
return "institution/institutionadd";
}
/**
* 執行添加操作
* @param map
* @param institution
* @param bindingResult
* @return
*/
@RequestMapping("/add")
public String add(Map<String, Object> map, @Valid Institution institution, BindingResult bindingResult) {
//檢查校驗是否出錯
if(bindingResult.hasErrors()){
List<ObjectError> list = bindingResult.getAllErrors();
ObjectError oe = list.get(0);
//校驗失敗信息
map.put("result", false);
map.put("msg", oe.getDefaultMessage() + "添加組織機構[" + institution.getInstname() + "]失敗!");
} else {
//功能名稱查重
boolean hasSame = institutionService.hasSameInstitution(null, institution.getInstname());
if (!hasSame) { //功能名稱不重復
//保存功能信息,拿到添加操作的結果
boolean result = institutionService.addInstitution(institution);
map.put("result", result);
//根據操作結果生成提示信息
if (result) { //添加成功且無重復
map.put("msg", "添加組織機構[" + institution.getInstname() + "]成功!");
} else {
map.put("msg", "添加組織機構[" + institution.getInstname() + "]失敗!");
}
} else {
map.put("result", false);
map.put("msg", "組織機構名稱[" + institution.getInstname() + "]重復,添加組織機構失敗!");
}
}
return "forward:/institution/institutions";
}
/**
* 模糊查詢
* @param map 攜帶查詢結果和參數
* @param pageNo 目標頁
* @param pageCount 分頁顯示記錄數
* @param keyword 搜索關鍵字
* @return
*/
@RequestMapping("/institutions")
public String institutions(Map<String, Object> map,
@RequestParam(value="pageNo", defaultValue="1", required=false) Integer pageNo,
@RequestParam(value="pageCount", defaultValue="10", required=false) Integer pageCount,
@RequestParam(value="keyword", required=false) String keyword) {
// 引入PageHelper分頁插件
// 在查詢之前只需要調用,傳入頁碼,以及每頁的大小
PageMethod.startPage(pageNo, pageCount);
// 分頁查詢得到結果集
List<Institution> institutions;
if (StringUtils.hasText(keyword)) {
Institution institution = new Institution();
institution.setInstname(keyword);
institutions = institutionService.findByKeyword(institution);
} else {
institutions = institutionService.findByKeyword(null);
}
// 使用pageInfo包裝查詢后的結果,只需要將pageInfo交給頁面就行了。
// 封裝了詳細的分頁信息,包括有我們查詢出來的數據,傳入連續顯示的頁數
PageInfo<Institution> page = new PageInfo<Institution>(institutions, 5);
//保存結果集帶到頁面顯示
map.put("page", page);
map.put("pageNo", pageNo);
map.put("pageCount", pageCount);
//保存模糊查詢條件以便回顯
map.put("keyword", keyword);
return "institution/institutionManage";
}
}
? LoginController.java
package cn.edu.nuc.article.controller;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.edu.nuc.article.entity.Function;
import cn.edu.nuc.article.entity.Role;
import cn.edu.nuc.article.entity.User;
import cn.edu.nuc.article.service.ArticleService;
import cn.edu.nuc.article.service.RoleService;
import cn.edu.nuc.article.service.UserService;
import cn.edu.nuc.article.util.CodeUtil;
import cn.edu.nuc.article.util.MD5Helper;
/**
* 用戶登錄和加載首頁Controller
*
*/
@Controller
public class LoginController {
/**
* 用戶業務
*/
@Autowired
private UserService userService;
/**
* 角色業務
*/
@Autowired
private RoleService roleService;
/**
* 公文Service
*/
@Autowired
private ArticleService articleService;
/**
* 獲取驗證碼
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
@RequestMapping(value = "/captcha", method = RequestMethod.GET)
@ResponseBody
public void captcha(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
CodeUtil.drawCode(request, response);
}
/**
* 用戶注銷
* @param session
* @return
*/
@RequestMapping("/logout")
public String logout(HttpSession session) {
//移除user屬性
session.removeAttribute("user");
//注銷Session
session.invalidate();
//返回登錄界面
return "redirect:/login.jsp";
}
/**
* 用戶登錄操作
* @param map 保存結果集
* @param session 存取用戶信息
* @param loginname 提交的登錄名
* @param password 提交的密碼
* @param code 提交的驗證碼
* @return
*/
@RequestMapping("/login")
public String userLogin(Map<String, Object> map, HttpSession session,
String loginname, String password, String code) {
//1.首先檢查登錄名、密碼和驗證碼用戶是否都填寫了,如果有一樣沒填寫就直接打回去
if (!StringUtils.hasText(loginname) || !StringUtils.hasText(password)
|| !StringUtils.hasText(code)) {
//1.1 告訴用戶登陸失敗,這三個字段都是必填項
map.put("msg", "登錄名、密碼和驗證碼都是必填項!");
map.put("result", false);
//1.2 直接跳回登錄界面
return "forward:/login.jsp";
}
//2.檢查驗證碼填寫是否正確,如不正確,也要打回去
String randomString = (String) session.getAttribute("code");
if (!randomString.equalsIgnoreCase(code)) {
//2.1 告訴用戶驗證碼輸入錯誤
map.put("msg", "驗證碼輸入錯誤!");
map.put("result", false);
//2.2 直接跳回登錄界面
return "forward:/login.jsp";
}
//3.檢查用戶輸入的賬號是否正確
//3.1 去數據庫查詢用戶名和密碼的組合
//對用戶輸入的密碼明文進行加密,獲得密文
MD5Helper md5Helper = new MD5Helper();
String afterEncode = md5Helper.getTwiceMD5ofString(password);
//檢查用戶名密碼(直接用密文查詢)
User user = userService.loginValidate(loginname, afterEncode);
//3.2 檢查登錄驗證是否通過,根據結果跳轉
if(user != null) {
//3.2.1 驗證通過
//3.2.1.1 如果驗證通過,就要把用戶信息存入Session,供以后登陸攔截檢查
session.setAttribute("user", user);
//3.2.1.2 跳轉到首頁
return "forward:/toIndex";
} else {
//3.2.2 驗證不通過
//3.2.2.1 提示用戶登陸失敗原因:用戶名密碼組合不正確
map.put("msg", "登錄名密碼組合輸入有誤或登錄名不存在!");
map.put("result", false);
return "forward:/login.jsp";
}
}
/**
* 訪問首頁
* @return
*/
@RequestMapping("/toIndex")
public String toIndex(Map<String, Object> map, HttpSession session) {
//1.從Session中加載出用戶的信息
User user = (User) session.getAttribute("user");
//2.通過用戶信息找到用戶的角色信息
Role role = user.getRole();
//3.通過角色信息查出角色下面的功能
List<Function> functions = roleService.findByIdCascade(role.getRoleid()).getFunctionList();
map.put("functionList", functions);
return "index";
}
/**
* 訪問歡迎頁
* @param map
* @return
*/
@RequestMapping("/toWelcome")
public String toWelcome(Map<String, Object> map, HttpSession session) {
//1.從Session中取出用戶信息,并得到用戶id和角色id
User user = (User) session.getAttribute("user");
Integer userId = user.getUserid();
Integer roleid = user.getRoleId();
//2.找出要統計的4個數字
//2.1 找出待處理公文數量
Long dealcount = null;
if (roleid == 1 || roleid == 2) {
dealcount = articleService.getDealCount(userId);
}
//2.2 找出審核駁回公文數量
Long failcount = articleService.getFailCount(userId);
//2.3 找出待接收公文數量
Long receivecount = articleService.getReceivedCount(userId);
//2.4 找出等待審核通過公文數量
Long waitcount = articleService.getWaitCount(userId);
//3 保存查詢結果
map.put("dealcount", dealcount);
map.put("failcount", failcount);
map.put("receivecount", receivecount);
map.put("waitcount", waitcount);
//4.返回首頁
return "home";
}
}
? RoleController.java
package cn.edu.nuc.article.controller;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import cn.edu.nuc.article.entity.Function;
import cn.edu.nuc.article.entity.Role;
import cn.edu.nuc.article.service.FunctionService;
import cn.edu.nuc.article.service.RoleService;
/**
* 角色Controller
*
*/
@Controller
@RequestMapping("/role")
public class RoleController {
/**
* 角色Service
*/
@Autowired
private RoleService roleService;
/**
* 功能Service
*/
@Autowired
private FunctionService functionService;
/**
* 更新權限
* @param map
* @param roleid 角色id
* @param funids 用戶選中的權限id
* @return
*/
@RequestMapping("/updateRoleRight")
public String updateRoleRight(Map<String, Object> map, Integer roleid, Integer funids[]) {
//查出角色信息
Role role = roleService.findById(roleid);
//修改權限列表
boolean result = roleService.updateRoleright(roleid, funids);
map.put("result", result);
if (result) {
map.put("msg", "修改角色[" + role.getRolename() + "]的權限信息成功!");
} else {
map.put("msg", "修改角色[" + role.getRolename() + "]的權限信息失敗!");
}
return "forward:/role/roles";
}
/**
* 進入權限頁面
* @return
*/
@RequestMapping("/toRoleRight")
public String toRoleRight(Map<String, Object> map, Integer roleid) {
//得到權限列表
Role role = roleService.findByIdCascade(roleid);
map.put("role", role);
//得到所有功能信息
List<Function> functions = functionService.getFunctionList(null);
map.put("functionList", functions);
return "role/roleright";
}
/**
* 進入修改頁面
* @return
*/
@RequestMapping("/toModify")
public String toModify(Map<String, Object> map, Integer roleid) {
Role role = roleService.findById(roleid);
map.put("role", role);
return "role/rolemodify";
}
/**
* 修改角色
* @return
*/
@RequestMapping("/modifyRole")
public String modifyRole(Map<String, Object> map, @Valid Role role, BindingResult bindingResult) {
//檢查校驗是否出錯
if(bindingResult.hasErrors()){
List<ObjectError> list = bindingResult.getAllErrors();
ObjectError oe = list.get(0);
//校驗失敗信息
map.put("result", false);
map.put("msg", oe.getDefaultMessage() + "修改角色[" + role.getRolename() + "]失敗!");
} else {
//功能名稱查重
boolean hasSame = roleService.hasSameRole(role.getRoleid(), role.getRolename());
if (!hasSame) { //功能名稱不重復
//保存功能信息,拿到修改操作的結果
boolean result = roleService.updateRole(role);
map.put("result", result);
//根據操作結果生成提示信息
if (result) { //修改成功且無重復
map.put("msg", "修改角色[" + role.getRolename() + "]成功!");
} else {
map.put("msg", "修改角色[" + role.getRolename() + "]失敗!");
}
} else {
map.put("result", false);
map.put("msg", "角色名稱[" + role.getRolename() + "]重復,修改角色失敗!");
}
}
return "forward:/role/roles";
}
/**
* 進入添加頁面
* @return
*/
@RequestMapping("/toAdd")
public String toAdd() {
return "role/roleadd";
}
/**
* 添加角色
* @return
*/
@RequestMapping("/addRole")
public String addRole(Map<String, Object> map, @Valid Role role, BindingResult bindingResult) {
//檢查校驗是否出錯
if(bindingResult.hasErrors()){
List<ObjectError> list = bindingResult.getAllErrors();
ObjectError oe = list.get(0);
//校驗失敗信息
map.put("result", false);
map.put("msg", oe.getDefaultMessage() + "添加角色[" + role.getRolename() + "]失敗!");
} else {
//功能名稱查重
boolean hasSame = roleService.hasSameRole(null, role.getRolename());
if (!hasSame) { //功能名稱不重復
//保存功能信息,拿到添加操作的結果
boolean result = roleService.addRole(role);
map.put("result", result);
//根據操作結果生成提示信息
if (result) { //添加成功且無重復
map.put("msg", "添加角色[" + role.getRolename() + "]成功!");
} else {
map.put("msg", "添加角色[" + role.getRolename() + "]失敗!");
}
} else {
map.put("result", false);
map.put("msg", "角色名稱[" + role.getRolename() + "]重復,添加角色失敗!");
}
}
return "forward:/role/roles";
}
/**
* 模糊查詢
* @param map 容器
* @param pageNo 目標頁
* @param pageCount 每頁記錄數
* @param roleid 角色id
* @return
*/
@RequestMapping("/roles")
public String roles(Map<String, Object> map,
@RequestParam(value="pageNo", defaultValue="1", required=false) Integer pageNo,
@RequestParam(value="pageCount", defaultValue="10", required=false) Integer pageCount,
@RequestParam(value="role_id", required=false) Integer role_id) {
// 引入PageHelper分頁插件
// 在查詢之前只需要調用,傳入頁碼,以及每頁的大小
PageMethod.startPage(pageNo, pageCount);
// 分頁查詢得到結果集
List<Role> roles;
if (role_id != null) {
Role role = new Role();
role.setRoleid(role_id);
roles = roleService.getByKeyword(role);
} else {
roles = roleService.getByKeyword(null);
}
// 使用pageInfo包裝查詢后的結果,只需要將pageInfo交給頁面就行了。
// 封裝了詳細的分頁信息,包括有我們查詢出來的數據,傳入連續顯示的頁數
PageInfo<Role> page = new PageInfo<Role>(roles, 5);
//保存結果集帶到頁面顯示
map.put("page", page);
map.put("pageNo", pageNo);
map.put("pageCount", pageCount);
map.put("allList", roleService.getByKeyword(null));
//保存模糊查詢條件以便回顯
map.put("role_id", role_id);
return "role/roleManage";
}
}
? UserController.java
package cn.edu.nuc.article.controller;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import cn.edu.nuc.article.entity.Institution;
import cn.edu.nuc.article.entity.Role;
import cn.edu.nuc.article.entity.User;
import cn.edu.nuc.article.service.InstitutionService;
import cn.edu.nuc.article.service.RoleService;
import cn.edu.nuc.article.service.UserService;
import cn.edu.nuc.article.util.MD5Helper;
import cn.edu.nuc.article.validategroup.UserValidateGroupForInsert;
import cn.edu.nuc.article.validategroup.UserValidateGroupForPasswordModify;
import cn.edu.nuc.article.validategroup.UserValidateGroupForUpdate;
import cn.edu.nuc.article.validategroup.UserValidateGroupForUserModify;
/**
* 用戶Controller
*
*/
@Controller
@RequestMapping("/user")
public class UserController {
/**
* 用戶Service
*/
@Autowired
private UserService userService;
/**
* 角色Service
*/
@Autowired
private RoleService roleService;
/**
* 機構service
*/
@Autowired
private InstitutionService institutionService;
/**
* 執行批量添加操作
* @param map 回傳參數用的map
* @param file 用戶上傳的Excel工作簿
* @return
* @throws Exception
*/
@RequestMapping("/addBatch")
public String addBatch(Map<String, Object> map, MultipartFile file) throws Exception {
//1.檢測文件是否上傳
if (file != null && file.getSize() == 0) { //文件沒上傳
map.put("result", false);
map.put("msg", "您沒有上傳Excel工作簿文件!");
return "forward:/user/toAddBatch";
}
//2.判斷是否是Excel文件,如果不是就打回去
if (!"application/vnd.ms-excel".equals(file.getContentType())) {
map.put("result", false);
map.put("msg", "您上傳的不是Excel工作簿文件!");
return "forward:/user/toAddBatch";
}
//3.解析excel保存用戶信息
if (!userService.addUserBatch(file.getInputStream())) {
map.put("result", false);
map.put("msg", "批量添加失敗!");
return "forward:/user/toAddBatch";
}
//4.如果操作成功,跳回到列表
map.put("result", true);
map.put("msg", "批量添加成功!");
return "forward:/user/users";
}
/**
* 下載用戶信息填寫模板使用說明
* @param httpServletResponse response對象
* @return
* @throws Exception
*/
@RequestMapping("/downloadReadFile")
public ResponseEntity<byte[]> downloadReadFile(
HttpServletResponse httpServletResponse) throws Exception {
byte [] body = null;
//獲得輸入流
InputStream in = this.getClass().getClassLoader().getResourceAsStream("excel/說明.docx");
body = new byte[in.available()];
in.read(body);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename="
+ new String("說明.docx".getBytes(), "ISO-8859-1"));
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> response =
new ResponseEntity<byte[]>(body, headers, statusCode);
return response;
}
/**
* 下載用戶信息填寫模板
* @param httpServletResponse response對象
* @return
* @throws Exception
*/
@RequestMapping("/downloadExcel")
public ResponseEntity<byte[]> downloadExcel(
HttpServletResponse httpServletResponse) throws Exception {
byte [] body = null;
//獲得輸入流
InputStream in = this.getClass().getClassLoader().getResourceAsStream("excel/用戶模板.xls");
body = new byte[in.available()];
in.read(body);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename="
+ new String("用戶模板.xls".getBytes(), "ISO-8859-1"));
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> response =
new ResponseEntity<byte[]>(body, headers, statusCode);
return response;
}
/**
* 進入批量添加界面
* @return
*/
@RequestMapping("/toAddBatch")
public String toAddBatch() {
return "user/useraddBatch";
}
/**
* 進入修改用戶密碼的界面
* @param map
* @param userid
* @return
*/
@RequestMapping("/toPasswordModify")
public String toPasswordModify(Map<String, Object> map) {
return "user/usermodifypassword-self";
}
/**
* 用戶修改自己的密碼
* @param map
* @param userid
* @return
*/
@RequestMapping("/modifyPassword")
public String modifyPassword(Map<String, Object> map, HttpSession session,
//指定由哪個校驗組校驗
@Validated(value=UserValidateGroupForPasswordModify.class) User user,
BindingResult bindingResult) {
//檢查校驗是否出錯
if(bindingResult.hasErrors()){
List<ObjectError> list = bindingResult.getAllErrors();
ObjectError oe = list.get(0);
//校驗失敗信息
map.put("result", false);
map.put("msg", oe.getDefaultMessage() + "修改密碼失敗!");
} else {
//檢查用戶的原密碼輸對沒有
User sessionUser = (User) session.getAttribute("user");
if (sessionUser.getPassword().equals(user.getOldPassword())) { //用戶輸對了舊密碼
if (sessionUser.getPassword().equals(user.getPassword())) { //用戶輸入的新密碼和原密碼一致
map.put("msg", "新密碼不能與舊密碼相同!");
} else {
//對新密碼加密
if (StringUtils.hasText(user.getPassword())) {
String original = user.getPassword();
MD5Helper md5Helper = new MD5Helper();
String afterEncodepassword = md5Helper.getTwiceMD5ofString(original);
user.setPassword(afterEncodepassword);
}
user.setUserid(sessionUser.getUserid());
//保存用戶信息,拿到修改操作的結果
boolean result = userService.updateUser(user);
map.put("result", result);
//根據操作結果生成提示信息
if (result) { //修改成功且無重復
//更新Session數據
session.setAttribute("user", userService.findbyId(sessionUser.getUserid()));
map.put("msg", "修改密碼成功!");
} else {
map.put("msg", "系統出現錯誤,修改密碼失敗!");
}
}
} else { //用戶沒輸對
map.put("msg", "您輸入的舊密碼不正確,修改密碼失敗!");
}
}
return "forward:/user/viewSelf";
}
/**
* 進入修改用戶個人信息的界面
* @param map
* @param userid
* @return
*/
@RequestMapping("/toModifySelf")
public String toModifySelf(Map<String, Object> map) {
return "user/usermodify-self";
}
/**
* 用戶修改自己的信息
* @param map
* @param userid
* @return
*/
@RequestMapping("/modifyself")
public String modifyself(Map<String, Object> map, HttpSession session,
//指定由哪個校驗組校驗
@Validated(value=UserValidateGroupForUserModify.class) User user,
BindingResult bindingResult) {
//檢查校驗是否出錯
if(bindingResult.hasErrors()){
List<ObjectError> list = bindingResult.getAllErrors();
ObjectError oe = list.get(0);
//校驗失敗信息
map.put("result", false);
map.put("msg", oe.getDefaultMessage() + "修改個人信息失敗!");
} else {
//保存用戶信息,拿到修改操作的結果
boolean result = userService.updateUser(user);
map.put("result", result);
//根據操作結果生成提示信息
if (result) { //修改成功且無重復
//更新Session的數據
session.setAttribute("user", userService.findbyId(user.getUserid()));
map.put("msg", "修改個人信息成功!");
} else {
map.put("msg", "修改個人信息失敗!");
}
}
return "forward:/user/viewSelf";
}
/**
* 用戶查看自己信息
* @param map
* @param userid
* @return
*/
@RequestMapping("/viewSelf")
public String viewSelf(Map<String, Object> map, HttpSession session) {
//加載出所有沒有被禁用的機構
Institution institution = new Institution();
institution.setInststate(1);
List<Institution> institutions = institutionService.findByKeyword(institution);
map.put("institutionList", institutions);
return "user/userview-self";
}
/**
* 管理員查看用戶詳細信息
* @param map
* @param userid
* @return
*/
@RequestMapping("/toView")
public String toView(Map<String, Object> map, Integer userid) {
loadUserInfo(map, userid);
return "user/userview";
}
/**
* 進入修改用戶界面
* @param map
* @return
*/
@RequestMapping("/toModify")
public String toModify(Map<String, Object> map, Integer userid) {
loadUserInfo(map, userid);
return "user/usermodify";
}
/**
* 抽取出來的方法:加載用戶信息
* @param map
* @param userid
*/
private void loadUserInfo(Map<String, Object> map, Integer userid) {
//1.加載出所有沒有被禁用的角色供用戶選擇
Role role = new Role();
role.setRolestate(1);
List<Role> roles = roleService.getByKeyword(role);
map.put("roleList", roles);
//2.加載出所有沒有被禁用的機構
Institution institution = new Institution();
institution.setInststate(1);
List<Institution> institutions = institutionService.findByKeyword(institution);
map.put("institutionList", institutions);
//3.加載出待修改記錄
User user = userService.findbyId(userid);
map.put("user", user);
}
/**
* 修改用戶信息
* @param map
* @param user
* @param bindingResult
* @return
*/
@RequestMapping("/modify")
public String modify(Map<String, Object> map,
//指定由哪個校驗組校驗
@Validated(value=UserValidateGroupForUpdate.class) User user,
BindingResult bindingResult) {
//檢查校驗是否出錯
if(bindingResult.hasErrors()){
List<ObjectError> list = bindingResult.getAllErrors();
ObjectError oe = list.get(0);
//校驗失敗信息
map.put("result", false);
map.put("msg", oe.getDefaultMessage() + "修改用戶[" + user.getUsertruename() + "]失敗!");
} else {
//登錄名查重
boolean hasSame = userService.hasSameName(user.getUserid(), user.getLoginname());
if (!hasSame) { //登錄名名稱不重復
//如果設置了新密碼則需要對其加密
if (StringUtils.hasText(user.getPassword())) {
String original = user.getPassword();
MD5Helper md5Helper = new MD5Helper();
String afterEncodepassword = md5Helper.getTwiceMD5ofString(original);
user.setPassword(afterEncodepassword);
}
//保存用戶信息,拿到修改操作的結果
boolean result = userService.updateUser(user);
map.put("result", result);
//根據操作結果生成提示信息
if (result) { //修改成功且無重復
map.put("msg", "修改用戶[" + user.getUsertruename() + "]成功!");
} else {
map.put("msg", "修改用戶[" + user.getUsertruename() + "]失敗!");
}
} else {
map.put("result", false);
map.put("msg", "用戶登錄名[" + user.getUsertruename() + "]重復,修改用戶失敗!");
}
}
return "forward:/user/users";
}
/**
* 進入添加單個用戶界面
* @param map
* @return
*/
@RequestMapping("/toAdd")
public String toAdd(Map<String, Object> map) {
//1.加載出所有沒有被禁用的角色供用戶選擇
Role role = new Role();
role.setRolestate(1);
List<Role> roles = roleService.getByKeyword(role);
map.put("roleList", roles);
//2.加載出所有沒有被禁用的機構
Institution institution = new Institution();
institution.setInststate(1);
List<Institution> institutions = institutionService.findByKeyword(institution);
map.put("institutionList", institutions);
return "user/useradd";
}
@RequestMapping("/add")
public String add(Map<String, Object> map,
//指定由固定的校驗組校驗
@Validated(value = UserValidateGroupForInsert.class) User user,
BindingResult bindingResult) {
//檢查校驗是否出錯
if(bindingResult.hasErrors()){
List<ObjectError> list = bindingResult.getAllErrors();
ObjectError oe = list.get(0);
//校驗失敗信息
map.put("result", false);
map.put("msg", oe.getDefaultMessage() + "添加用戶[" + user.getUsertruename() + "]失敗!");
} else {
//登錄名查重
boolean hasSame = userService.hasSameName(null, user.getLoginname());
if (!hasSame) { //登錄名不重復
//如果設置了新密碼則需要對其加密
if (StringUtils.hasText(user.getPassword())) {
String original = user.getPassword();
MD5Helper md5Helper = new MD5Helper();
String afterEncodepassword = md5Helper.getTwiceMD5ofString(original);
user.setPassword(afterEncodepassword);
}
//保存用戶信息,拿到添加操作的結果
boolean result = userService.addUser(user);
map.put("result", result);
//根據操作結果生成提示信息
if (result) { //添加成功且無重復
map.put("msg", "添加用戶[" + user.getUsertruename() + "]成功!");
} else {
map.put("msg", "添加用戶[" + user.getUsertruename() + "]失敗!");
}
} else {
map.put("result", false);
map.put("msg", "用戶登錄名[" + user.getUsertruename() + "]重復,添加用戶失敗!");
}
}
return "forward:/user/users";
}
/**
* 系統管理員查看用戶列表
* @param map 攜帶查詢結果和參數
* @param pageNo 目標頁
* @param pageCount 每頁顯示多少記錄
* @param keyword 查詢關鍵字
* @return
*/
@RequestMapping("/users")
public String users(Map<String, Object> map,
@RequestParam(value="pageNo", defaultValue="1", required=false) Integer pageNo,
@RequestParam(value="pageCount", defaultValue="10", required=false) Integer pageCount,
@RequestParam(value="keyword", required=false) String keyword) {
// 引入PageHelper分頁插件
// 在查詢之前只需要調用,傳入頁碼,以及每頁的大小
PageMethod.startPage(pageNo, pageCount);
// 分頁查詢得到結果集
List<User> users;
if (StringUtils.hasText(keyword)) {
User user = new User();
user.setUsertruename(keyword);
users = userService.findByKeyword(user);
} else {
users = userService.findByKeyword(null);
}
// 使用pageInfo包裝查詢后的結果,只需要將pageInfo交給頁面就行了。
// 封裝了詳細的分頁信息,包括有我們查詢出來的數據,傳入連續顯示的頁數
PageInfo<User> page = new PageInfo<User>(users, 5);
//保存結果集帶到頁面顯示
map.put("page", page);
map.put("pageNo", pageNo);
map.put("pageCount", pageCount);
//保存模糊查詢條件以便回顯
map.put("keyword", keyword);
return "user/userManage";
}
}
4.燃盡圖

5.今日工作量

浙公網安備 33010602011771號