SysDictController.java 16.2 KB
Newer Older
1 2 3
package org.jeecg.modules.system.controller;


4
import java.util.*;
5 6

import javax.servlet.http.HttpServletRequest;
7
import javax.servlet.http.HttpServletResponse;
8

9
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
10
import org.apache.shiro.SecurityUtils;
11
import org.jeecg.common.api.vo.Result;
12 13
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
14
import org.jeecg.common.system.query.QueryGenerator;
15
import org.jeecg.common.system.vo.DictModel;
16
import org.jeecg.common.system.vo.LoginUser;
17
import org.jeecg.common.util.RedisUtil;
18
import org.jeecg.common.util.SqlInjectionUtil;
19 20
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysDict;
21
import org.jeecg.modules.system.entity.SysDictItem;
22
import org.jeecg.modules.system.model.SysDictTree;
23
import org.jeecg.modules.system.model.TreeSelectModel;
24
import org.jeecg.modules.system.service.ISysDictItemService;
25
import org.jeecg.modules.system.service.ISysDictService;
26 27 28 29 30 31 32
import org.jeecg.modules.system.vo.SysDictPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
33
import org.springframework.beans.factory.annotation.Autowired;
34
import org.springframework.cache.annotation.CacheEvict;
35
import org.springframework.data.redis.core.RedisTemplate;
36 37 38 39 40 41
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
42 43 44
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
45

46 47
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
48 49 50 51 52 53 54 55 56 57 58 59
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * 字典表 前端控制器
 * </p>
 *
60
 * @Author zhangweijian
61 62 63 64 65 66
 * @since 2018-12-28
 */
@RestController
@RequestMapping("/sys/dict")
@Slf4j
public class SysDictController {
67

68 69
	@Autowired
	private ISysDictService sysDictService;
70 71
	@Autowired
	private ISysDictItemService sysDictItemService;
72 73
	@Autowired
	public RedisTemplate<String, Object> redisTemplate;
74

75 76 77 78
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public Result<IPage<SysDict>> queryPageList(SysDict sysDict,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,HttpServletRequest req) {
		Result<IPage<SysDict>> result = new Result<IPage<SysDict>>();
79 80
		QueryWrapper<SysDict> queryWrapper = QueryGenerator.initQueryWrapper(sysDict, req.getParameterMap());
		Page<SysDict> page = new Page<SysDict>(pageNo, pageSize);
81
		IPage<SysDict> pageList = sysDictService.page(page, queryWrapper);
82 83 84 85
		log.debug("查询当前页:"+pageList.getCurrent());
		log.debug("查询当前页数量:"+pageList.getSize());
		log.debug("查询结果数量:"+pageList.getRecords().size());
		log.debug("数据总数:"+pageList.getTotal());
86 87 88 89
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
90

91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
	/**
	 * @功能:获取树形字典数据
	 * @param sysDict
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/treeList", method = RequestMethod.GET)
	public Result<List<SysDictTree>> treeList(SysDict sysDict,@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,HttpServletRequest req) {
		Result<List<SysDictTree>> result = new Result<>();
		LambdaQueryWrapper<SysDict> query = new LambdaQueryWrapper<>();
		// 构造查询条件
		String dictName = sysDict.getDictName();
		if(oConvertUtils.isNotEmpty(dictName)) {
			query.like(true, SysDict::getDictName, dictName);
		}
		query.orderByDesc(true, SysDict::getCreateTime);
		List<SysDict> list = sysDictService.list(query);
		List<SysDictTree> treeList = new ArrayList<>();
		for (SysDict node : list) {
			treeList.add(new SysDictTree(node));
		}
		result.setSuccess(true);
		result.setResult(treeList);
		return result;
	}
120

121 122
	/**
	 * 获取字典数据
123 124
	 * @param dictCode 字典code
	 * @param dictCode 表名,文本字段,code字段  | 举例:sys_user,realname,id
125 126 127
	 * @return
	 */
	@RequestMapping(value = "/getDictItems/{dictCode}", method = RequestMethod.GET)
128
	public Result<List<DictModel>> getDictItems(@PathVariable String dictCode) {
129
		log.info(" dictCode : "+ dictCode);
130 131
		Result<List<DictModel>> result = new Result<List<DictModel>>();
		List<DictModel> ls = null;
132
		try {
133 134 135
			if(dictCode.indexOf(",")!=-1) {
				//关联表字典(举例:sys_user,realname,id)
				String[] params = dictCode.split(",");
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
				
				if(params.length<3) {
					result.error500("字典Code格式不正确!");
					return result;
				}
				//SQL注入校验(只限制非法串改数据库)
				final String[] sqlInjCheck = {params[0],params[1],params[2]};
				SqlInjectionUtil.filterContent(sqlInjCheck);
				
				if(params.length==4) {
					//SQL注入校验(查询条件SQL 特殊check,此方法仅供此处使用)
					SqlInjectionUtil.specialFilterContent(params[3]);
					ls = sysDictService.queryTableDictItemsByCodeAndFilter(params[0],params[1],params[2],params[3]);
				}else if (params.length==3) {
					ls = sysDictService.queryTableDictItemsByCode(params[0],params[1],params[2]);
				}else{
152 153 154 155 156 157 158 159
					result.error500("字典Code格式不正确!");
					return result;
				}
			}else {
				//字典表
				 ls = sysDictService.queryDictItemsByCode(dictCode);
			}

160 161
			 result.setSuccess(true);
			 result.setResult(ls);
162
			 log.info(result.toString());
163
		} catch (Exception e) {
164
			log.error(e.getMessage(),e);
165 166 167
			result.error500("操作失败");
			return result;
		}
168

169 170
		return result;
	}
171

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
	/**
	 * 获取字典数据
	 * @param dictCode
	 * @return
	 */
	@RequestMapping(value = "/getDictText/{dictCode}/{key}", method = RequestMethod.GET)
	public Result<String> getDictItems(@PathVariable("dictCode") String dictCode, @PathVariable("key") String key) {
		log.info(" dictCode : "+ dictCode);
		Result<String> result = new Result<String>();
		String text = null;
		try {
			text = sysDictService.queryDictTextByKey(dictCode, key);
			 result.setSuccess(true);
			 result.setResult(text);
		} catch (Exception e) {
187
			log.error(e.getMessage(),e);
188 189 190 191 192
			result.error500("操作失败");
			return result;
		}
		return result;
	}
193

194 195 196 197 198 199 200 201 202 203
	/**
	 * @功能:新增
	 * @param sysDict
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public Result<SysDict> add(@RequestBody SysDict sysDict) {
		Result<SysDict> result = new Result<SysDict>();
		try {
			sysDict.setCreateTime(new Date());
204
			sysDict.setDelFlag(CommonConstant.DEL_FLAG_0);
205 206 207
			sysDictService.save(sysDict);
			result.success("保存成功!");
		} catch (Exception e) {
208
			log.error(e.getMessage(),e);
209 210 211 212
			result.error500("操作失败");
		}
		return result;
	}
213

214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
	/**
	 * @功能:编辑
	 * @param sysDict
	 * @return
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.PUT)
	public Result<SysDict> edit(@RequestBody SysDict sysDict) {
		Result<SysDict> result = new Result<SysDict>();
		SysDict sysdict = sysDictService.getById(sysDict.getId());
		if(sysdict==null) {
			result.error500("未找到对应实体");
		}else {
			sysDict.setUpdateTime(new Date());
			boolean ok = sysDictService.updateById(sysDict);
			if(ok) {
				result.success("编辑成功!");
			}
		}
		return result;
	}
234

235 236 237 238 239 240
	/**
	 * @功能:删除
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.DELETE)
241
	@CacheEvict(value=CacheConstant.SYS_DICT_CACHE, allEntries=true)
242 243
	public Result<SysDict> delete(@RequestParam(name="id",required=true) String id) {
		Result<SysDict> result = new Result<SysDict>();
244 245 246 247 248
		boolean ok = sysDictService.removeById(id);
		if(ok) {
			result.success("删除成功!");
		}else{
			result.error500("删除失败!");
249 250 251
		}
		return result;
	}
252

253 254 255 256 257 258
	/**
	 * @功能:批量删除
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
259
	@CacheEvict(value= CacheConstant.SYS_DICT_CACHE, allEntries=true)
260 261
	public Result<SysDict> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<SysDict> result = new Result<SysDict>();
262
		if(oConvertUtils.isEmpty(ids)) {
263 264
			result.error500("参数不识别!");
		}else {
265
			sysDictService.removeByIds(Arrays.asList(ids.split(",")));
266 267 268 269
			result.success("删除成功!");
		}
		return result;
	}
270

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
	/**
	 * @功能:刷新缓存
	 * @return
	 */
	@RequestMapping(value = "/refleshCache")
	public Result<?> refleshCache() {
		Result<?> result = new Result<SysDict>();
		//清空字典缓存
		Set keys = redisTemplate.keys(CacheConstant.SYS_DICT_CACHE + "*");
		Set keys2 = redisTemplate.keys(CacheConstant.SYS_DICT_TABLE_CACHE + "*");
		Set keys3 = redisTemplate.keys(CacheConstant.SYS_DEPARTS_CACHE + "*");
		Set keys4 = redisTemplate.keys(CacheConstant.SYS_DEPART_IDS_CACHE + "*");
		redisTemplate.delete(keys);
		redisTemplate.delete(keys2);
		redisTemplate.delete(keys3);
		redisTemplate.delete(keys4);
		return result;
	}

290 291 292 293 294 295
	/**
	 * 导出excel
	 *
	 * @param request
	 */
	@RequestMapping(value = "/exportXls")
296
	public ModelAndView exportXls(SysDict sysDict,HttpServletRequest request) {
297
		// Step.1 组装查询条件
298
		QueryWrapper<SysDict> queryWrapper = QueryGenerator.initQueryWrapper(sysDict, request.getParameterMap());
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
		//Step.2 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		List<SysDictPage> pageList = new ArrayList<SysDictPage>();

		List<SysDict> sysDictList = sysDictService.list(queryWrapper);
		for (SysDict dictMain : sysDictList) {
			SysDictPage vo = new SysDictPage();
			BeanUtils.copyProperties(dictMain, vo);
			// 查询机票
			List<SysDictItem> sysDictItemList = sysDictItemService.selectItemsByMainId(dictMain.getId());
			vo.setSysDictItemList(sysDictItemList);
			pageList.add(vo);
		}

		// 导出文件名称
		mv.addObject(NormalExcelConstants.FILE_NAME, "数据字典");
		// 注解对象Class
		mv.addObject(NormalExcelConstants.CLASS, SysDictPage.class);
		// 自定义表格参数
318 319
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("数据字典列表", "导出人:"+user.getRealname(), "数据字典"));
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
		// 导出数据列表
		mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		return mv;
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(2);
			params.setNeedSave(true);
			try {
				List<SysDictPage> list = ExcelImportUtil.importExcel(file.getInputStream(), SysDictPage.class, params);
				for (SysDictPage page : list) {
					SysDict po = new SysDict();
					BeanUtils.copyProperties(page, po);
					if(page.getDelFlag()==null){
					    po.setDelFlag(1);
                    }
					sysDictService.saveMain(po, page.getSysDictItemList());
				}
				return Result.ok("文件导入成功!");
			} catch (Exception e) {
354 355
				log.error(e.getMessage(),e);
				return Result.error("文件导入失败:"+e.getMessage());
356 357 358 359 360 361 362 363
			} finally {
				try {
					file.getInputStream().close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
364
		return Result.error("文件导入失败!");
365
	}
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
	
	/**
	 * 大数据量的字典表 走异步加载  即前端输入内容过滤数据 
	 * @param dictCode
	 * @return
	 */
	@RequestMapping(value = "/loadDict/{dictCode}", method = RequestMethod.GET)
	public Result<List<DictModel>> loadDict(@PathVariable String dictCode,@RequestParam(name="keyword") String keyword) {
		log.info(" 加载字典表数据,加载关键字: "+ keyword);
		Result<List<DictModel>> result = new Result<List<DictModel>>();
		List<DictModel> ls = null;
		try {
			if(dictCode.indexOf(",")!=-1) {
				String[] params = dictCode.split(",");
				if(params.length!=3) {
					result.error500("字典Code格式不正确!");
					return result;
				}
				ls = sysDictService.queryTableDictItems(params[0],params[1],params[2],keyword);
				result.setSuccess(true);
				result.setResult(ls);
				log.info(result.toString());
			}else {
				result.error500("字典Code格式不正确!");
			}
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
			return result;
		}

		return result;
	}
	
	/**
	 * 根据字典code加载字典text 返回
	 */
	@RequestMapping(value = "/loadDictItem/{dictCode}", method = RequestMethod.GET)
404 405
	public Result<List<String>> loadDictItem(@PathVariable String dictCode,@RequestParam(name="key") String key) {
		Result<List<String>> result = new Result<>();
406 407 408 409 410 411 412
		try {
			if(dictCode.indexOf(",")!=-1) {
				String[] params = dictCode.split(",");
				if(params.length!=3) {
					result.error500("字典Code格式不正确!");
					return result;
				}
413 414
				List<String> texts = sysDictService.queryTableDictByKeys(params[0], params[1], params[2], key.split(","));

415
				result.setSuccess(true);
416
				result.setResult(texts);
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
				log.info(result.toString());
			}else {
				result.error500("字典Code格式不正确!");
			}
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
			return result;
		}

		return result;
	}
	
	/**
	 * 根据表名——显示字段-存储字段 pid 加载树形数据
	 */
433
	@SuppressWarnings("unchecked")
434 435 436 437 438
	@RequestMapping(value = "/loadTreeData", method = RequestMethod.GET)
	public Result<List<TreeSelectModel>> loadDict(@RequestParam(name="pid") String pid,@RequestParam(name="pidField") String pidField,
			@RequestParam(name="tableName") String tbname,
			@RequestParam(name="text") String text,
			@RequestParam(name="code") String code,
439 440
			@RequestParam(name="hasChildField") String hasChildField,
			@RequestParam(name="condition") String condition) {
441
		Result<List<TreeSelectModel>> result = new Result<List<TreeSelectModel>>();
442 443 444 445 446
		Map<String, String> query = null;
		if(oConvertUtils.isNotEmpty(condition)) {
			query = JSON.parseObject(condition, Map.class);
		}
		List<TreeSelectModel> ls = sysDictService.queryTreeList(query,tbname, text, code, pidField, pid,hasChildField);
447 448 449 450
		result.setSuccess(true);
		result.setResult(ls);
		return result;
	}
451

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497

	/**
	 * 查询被删除的列表
	 * @return
	 */
	@RequestMapping(value = "/deleteList", method = RequestMethod.GET)
	public Result<List<SysDict>> deleteList() {
		Result<List<SysDict>> result = new Result<List<SysDict>>();
		List<SysDict> list = this.sysDictService.queryDeleteList();
		result.setSuccess(true);
		result.setResult(list);
		return result;
	}

	/**
	 * 物理删除
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/deletePhysic/{id}", method = RequestMethod.DELETE)
	public Result<?> deletePhysic(@PathVariable String id) {
		try {
			sysDictService.deleteOneDictPhysically(id);
			return Result.ok("删除成功!");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("删除失败!");
		}
	}

	/**
	 * 取回
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/back/{id}", method = RequestMethod.PUT)
	public Result<?> back(@PathVariable String id) {
		try {
			sysDictService.updateDictDelFlag(0,id);
			return Result.ok("操作成功!");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("操作失败!");
		}
	}

498
}