优化代码

This commit is contained in:
RuoYi
2018-06-15 15:25:59 +08:00
parent 81b1d1c219
commit 5f0fa0d42f
60 changed files with 169 additions and 671 deletions

View File

@ -1,78 +0,0 @@
package com.ruoyi.common.utils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import java.text.DecimalFormat;
import java.util.Date;
/**
* 导入Excel工具类
*/
public class ExcelImportUtils {
/** 是否是2003的excel返回true是2003Excel文件**/
public static boolean isExcel2003(String filePath){
return filePath.matches("^.+\\.(?i)(xls)$");
}
/** 是否是2007以上的excel返回true是2007Excel文件**/
public static boolean isExcel2007(String filePath){
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
/**
* 验证EXCEL文件
*
* @param filePath
* @return
*/
public static boolean validateExcel(String filePath) {
if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
return false;
}
return true;
}
/**
* 获取单元格的值
* @param cell
* @return
*/
public static String getCellValue(Cell cell) {
String value = "";
if (cell != null) {
switch(cell.getCellTypeEnum()){
case NUMERIC:// 数字
value = cell.getNumericCellValue()+ " ";
if(HSSFDateUtil.isCellDateFormatted(cell)){
Date date = cell.getDateCellValue();
if(date != null){
value = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,date); // 日期格式化
}else{
value = "";
}
}else {
// 解析cell时候 数字类型默认是double类型的 但是想要获取整数类型 需要格式化
value = new DecimalFormat("0").format(cell.getNumericCellValue());
}
break;
case STRING: // 字符串
value = cell.getStringCellValue();
break;
case BOOLEAN: // Boolean类型
value = cell.getBooleanCellValue()+"";
break;
case BLANK: // 空值
value = "";
break;
case ERROR: // 错误类型
value ="非法字符";
break;
default:
value = "未知类型";
break;
}
}
return value.trim();
}
}

View File

@ -40,7 +40,7 @@ public class JobController extends BaseController
}
@RequiresPermissions("monitor:job:list")
@GetMapping("/list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(Job job)
{

View File

@ -39,7 +39,7 @@ public class JobLogController extends BaseController
}
@RequiresPermissions("monitor:job:list")
@GetMapping("/list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(JobLog jobLog)
{

View File

@ -38,7 +38,7 @@ public class LogininforController extends BaseController
}
@RequiresPermissions("monitor:logininfor:list")
@GetMapping("/list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(Logininfor logininfor)
{

View File

@ -44,7 +44,7 @@ public class UserOnlineController extends BaseController
}
@RequiresPermissions("monitor:online:list")
@GetMapping("/list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(UserOnline userOnline)
{

View File

@ -39,7 +39,7 @@ public class OperlogController extends BaseController
}
@RequiresPermissions("monitor:operlog:list")
@GetMapping("/list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(OperLog operLog)
{

View File

@ -43,7 +43,7 @@ public class ConfigController extends BaseController
* 查询参数配置列表
*/
@RequiresPermissions("system:config:list")
@GetMapping("/list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(Config config)
{

View File

@ -39,7 +39,7 @@ public class DictDataController extends BaseController
return prefix + "/data";
}
@GetMapping("/list")
@PostMapping("/list")
@RequiresPermissions("system:dict:list")
@ResponseBody
public TableDataInfo list(DictData dictData)

View File

@ -39,7 +39,7 @@ public class DictTypeController extends BaseController
return prefix + "/type";
}
@GetMapping("/list")
@PostMapping("/list")
@RequiresPermissions("system:dict:list")
@ResponseBody
public TableDataInfo list(DictType dictType)

View File

@ -40,7 +40,7 @@ public class PostController extends BaseController
}
@RequiresPermissions("system:post:list")
@GetMapping("/list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(Post post)
{

View File

@ -1,6 +1,5 @@
package com.ruoyi.project.system.user.controller;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.web.controller.BaseController;
@ -14,15 +13,11 @@ import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.domain.UserStatus;
import com.ruoyi.project.system.user.service.IUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
@ -34,7 +29,6 @@ import java.util.List;
@RequestMapping("/system/user")
public class UserController extends BaseController
{
private static final Logger log = LoggerFactory.getLogger(UserController.class);
private String prefix = "system/user";
@Autowired
@ -54,7 +48,7 @@ public class UserController extends BaseController
}
@RequiresPermissions("system:user:list")
@GetMapping("/list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(User user)
{
@ -171,28 +165,6 @@ public class UserController extends BaseController
return userService.saveUser(user) > 0 ? Message.success() : Message.error();
}
/**
* 批量新增用户
*/
@RequiresPermissions("system:user:batchAdd")
@Log(title = "系统管理", action = "用户管理-批量新增用户")
@PostMapping("/batchAdd")
@Transactional(rollbackFor = Exception.class)
@ResponseBody
public Message batchAdd( @RequestParam("uploadfile") MultipartFile file)
{
try {
if(!file.isEmpty()){
int rows=userService.batchImportUsers(file);
return Message.success(String.valueOf(rows));
}
return Message.error();
}catch (UserException e){
log.error("批量添加用户失败 !---{}", e.getMessage());
return Message.error(e.getMessage());
}
}
/**
* 校验用户名
*/

View File

@ -1,8 +1,6 @@
package com.ruoyi.project.system.user.service;
import com.ruoyi.project.system.user.domain.User;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
@ -28,7 +26,7 @@ public interface IUserService
* @return 用户对象信息
*/
public User selectUserByLoginName(String userName);
/**
* 通过手机号码查询用户
*
@ -36,7 +34,7 @@ public interface IUserService
* @return 用户对象信息
*/
public User selectUserByPhoneNumber(String phoneNumber);
/**
* 通过邮箱查询用户
*
@ -101,7 +99,6 @@ public interface IUserService
*/
public String checkLoginNameUnique(String loginName);
/**
* 校验手机号码是否唯一
*
@ -110,7 +107,6 @@ public interface IUserService
*/
public String checkPhoneUnique(User user);
/**
* 校验email是否唯一
*
@ -134,12 +130,4 @@ public interface IUserService
* @return 结果
*/
public String selectUserPostGroup(Long userId);
/**
* Excel批量导入用户
* @param myFile
* @return
*/
public int batchImportUsers(MultipartFile myFile);
}

View File

@ -1,13 +1,9 @@
package com.ruoyi.project.system.user.service;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.common.utils.ExcelImportUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.shiro.service.PasswordService;
import com.ruoyi.project.system.dept.domain.Dept;
import com.ruoyi.project.system.dept.service.IDeptService;
import com.ruoyi.project.system.post.domain.Post;
import com.ruoyi.project.system.post.mapper.PostMapper;
import com.ruoyi.project.system.role.domain.Role;
@ -18,18 +14,8 @@ import com.ruoyi.project.system.user.domain.UserRole;
import com.ruoyi.project.system.user.mapper.UserMapper;
import com.ruoyi.project.system.user.mapper.UserPostMapper;
import com.ruoyi.project.system.user.mapper.UserRoleMapper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.*;
/**
@ -40,7 +26,6 @@ import java.util.*;
@Service("userService")
public class UserServiceImpl implements IUserService
{
private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
@Autowired
private UserMapper userMapper;
@ -59,10 +44,6 @@ public class UserServiceImpl implements IUserService
@Autowired
private PasswordService passwordService;
@Autowired
private IDeptService deptService;
/**
* 根据条件分页查询用户对象
*
@ -195,248 +176,6 @@ public class UserServiceImpl implements IUserService
return count;
}
/**
* 根据Execl 批量保存用户
* 1. 使用HSSFWorkbook 打开或者创建 “Excel对象”
* 2. 用HSSFWorkbook返回对象或者创建sheet对象
* 3. 用sheet返回行对象用行对象得到Cell对象
* 4. 对Cell对象进行读写
* @param myFile
* @return
*/
@Override
public int batchImportUsers(MultipartFile myFile) {
//Excel工作簿
Workbook workbook=null;
//获取文件名
String filename=myFile.getOriginalFilename();
log.info("【ExeclfileName】={}",filename);
if(StringUtils.isNotEmpty(filename)){
//根据文件名判断文件是2003版本还是2007版本
if(ExcelImportUtils.isExcel2003(filename)){
try {
workbook=new HSSFWorkbook(myFile.getInputStream());//2003版本
}catch (IOException e){
throw new UserException("user.import.excel.fileinput.error",null);
}
}else if(ExcelImportUtils.isExcel2007(filename)){
try {
workbook=new XSSFWorkbook(myFile.getInputStream());//2007以上版本
}catch (IOException e){
throw new UserException("user.import.excel.fileinputx.error",null);
}
}else{
throw new UserException("user.import.excel.filetype.error",null);
}
}else {
throw new UserException("user.import.excel.file.error",null);
}
//得到第一个sheet
Sheet sheet = workbook.getSheetAt(0);
//得到Excel的行数
int totalRows = sheet.getLastRowNum();
log.info("【rows】{}",totalRows);
//新建用户list
List<User> users=new ArrayList<User>();
List<Dept> depts=new ArrayList<Dept>();
List<Role> roles=new ArrayList<Role>();
List<Post> posts=new ArrayList<Post>();
//如果行数为空
/**
* getPhysicalNumberOfRows
*
* 获取有记录的行数最后有数据的行是第n行前面有m行是空行没数据则返回n-m
*/
if((totalRows==0)&&(sheet.getPhysicalNumberOfRows()==0)){
throw new UserException("user.import.excel.null",null);
}else if((totalRows==0)&&(sheet.getPhysicalNumberOfRows()==1)){
throw new UserException("user.import.excel.data.null",null);
} else{
//获取全部部门信息
depts=deptService.selectDeptAll();
//获取全部角色信息
roles=roleMapper.selectRolesAll();
//获取全部岗位信息
posts=postMapper.selectPostAll();
}
for(int i=1;i<=totalRows;i++){
Row row = sheet.getRow(i);
if(row!=null){
User user=new User();
//登录名(用户名)
String userName=ExcelImportUtils.getCellValue(row.getCell(0));
if(userName.isEmpty()){
continue;
}else{
//判断用户名是否唯一
if(checkLoginNameUnique(userName).equals(UserConstants.USER_NAME_UNIQUE)){
user.setLoginName(userName);
}else {
log.error("【rows】{}行用户名{}已经存在",i+1,userName);
continue;
}
}
//姓名
String userRealName=ExcelImportUtils.getCellValue(row.getCell(1));
user.setUserName(userRealName);
//性别
String userSex=ExcelImportUtils.getCellValue(row.getCell(2));
if(StringUtils.isNotEmpty(userSex)){
if(userSex.equals("")){
user.setSex("0");
}else if(userSex.equals("")){
user.setSex("1");
}else {
user.setSex("2");
}
}
//密码
String passWord=ExcelImportUtils.getCellValue(row.getCell(3));
if(passWord.isEmpty()){
continue;
}else{
user.randomSalt();
user.setPassword(passwordService.encryptPassword(userName, passWord, user.getSalt()));
}
//部门
String dept=ExcelImportUtils.getCellValue(row.getCell(4));
if(StringUtils.isNotEmpty(dept)){
for (int k=0;k<depts.size();k++){
if(dept.equals(depts.get(k).getDeptName())){
user.setDeptId(depts.get(k).getDeptId());
break;
}
}
}
user.setCreateBy(ShiroUtils.getLoginName());
//角色--多个角色以","分割
String userRolesExcel=ExcelImportUtils.getCellValue(row.getCell(5));
if(StringUtils.isNotEmpty(userRolesExcel)){
//Set可以去掉重复的值
Set<Long> sets=new HashSet<Long>();
//判断是否有英文的"," 号
if(userRolesExcel.contains(",")){
List<String> results= Arrays.asList(userRolesExcel.split(","));
for(String s:results){
for(int l=0;l<roles.size();l++){
if(s.equals(roles.get(l).getRoleName())){
sets.add(roles.get(l).getRoleId());
break;
}
}
}
}else {
for(int j=0;j<roles.size();j++){
if(userRolesExcel.equals(roles.get(j).getRoleName())){
sets.add(roles.get(j).getRoleId());
break;
}
}
}
for(Long longTes:sets){
log.info("用户名={},角色ID={}",userName,longTes);
}
user.setRoleIds(sets.toArray(new Long[sets.size()]));
}
//岗位--多个岗位以","分割
String userPostExcel=ExcelImportUtils.getCellValue(row.getCell(6));
if(StringUtils.isNotEmpty(userPostExcel)){
//去掉重复的值,
Set<Long> setPosts=new HashSet<Long>();
//判断是否有英文的"," 号
if(userPostExcel.contains(",")){
List<String> resultsp= Arrays.asList(userPostExcel.split(","));
for(String p:resultsp){
for(int h=0;h<posts.size();h++){
if(p.equals(posts.get(h).getPostName())){
setPosts.add(posts.get(h).getPostId());
break;
}
}
}
}else {
for(int m=0;m<posts.size();m++){
if(userPostExcel.equals(posts.get(m).getPostName())){
setPosts.add(posts.get(m).getPostId());
break;
}
}
}
for(Long longTest:setPosts){
log.info("用户名={},岗位ID={}",userName,longTest);
}
user.setPostIds(setPosts.toArray(new Long[setPosts.size()]));
}
//手机号
String phoneNumber=ExcelImportUtils.getCellValue(row.getCell(7));
if(StringUtils.isNotEmpty(phoneNumber)){
//验证是否是手机号
if(phoneNumber.matches(UserConstants.MOBILE_PHONE_NUMBER_PATTERN)){
user.setPhonenumber(phoneNumber);
}
}
//邮箱
String userEmail=ExcelImportUtils.getCellValue(row.getCell(8));
if(StringUtils.isNotEmpty(userEmail)){
//验证是否是邮箱
if(userEmail.matches(UserConstants.EMAIL_PATTERN)){
user.setEmail(userEmail);
}
}
users.add(user);
}
}
//实际添加行数
int realRow=0;
//如果添加的列表不为空
if(users.size()>0){
//批量插入用户
realRow=userMapper.batchAddUser(users);
}
log.info("成功导入用户共{}个",realRow);
if(realRow>0){
//用户和角色关联
List<UserRole> userRoles=new ArrayList<UserRole>();
//用户和岗位关联
List<UserPost> userPosts=new ArrayList<UserPost>();
for(User test:users){
//添加用户-角色关联表
for(int q=0;q<test.getRoleIds().length;q++){
UserRole userRole=new UserRole();
userRole.setUserId(test.getUserId());
userRole.setRoleId(test.getRoleIds()[q]);
userRoles.add(userRole);
}
for(int r=0;r<test.getPostIds().length;r++){
UserPost userPost=new UserPost();
userPost.setUserId(test.getUserId());
userPost.setPostId(test.getPostIds()[r]);
userPosts.add(userPost);
}
}
//批量添加用户-角色关联数据
userRoleMapper.batchUserRole(userRoles);
log.info("成功导入用户-角色关联数据");
//批量添加用户-岗位关联数据
userPostMapper.batchUserPost(userPosts);
log.info("成功导入用户-岗位关联数据");
}
return realRow;
}
/**
* 修改用户信息
*

View File

@ -9,6 +9,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
@ -40,7 +41,7 @@ public class GenController extends BaseController
}
@RequiresPermissions("tool:gen:list")
@GetMapping("/list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(TableInfo tableInfo)
{