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";
}
}