【JeeSite】用户管理
組織機構使用ztree插件,加載數據時使用數據權限過濾(只能訪問登錄用戶的單位及其下屬單位), 點擊部門加載相應用戶。
<!-- 數據范圍過濾 -->?? BaseService.dataScopeFilter(user, "a", ""),
?? ${sqlMap.dsf}?? 比如使用jn_jsb登錄,生成的sqlMap.dsf? 是?? AND (a.id = '7' OR a.parent_ids LIKE '0,1,7,%' OR a.id IS NULL)? ,
這個靜態常量 DEL_FLAG_NORMAL 是在baseEntity里面, sqlMap 也是其中一個父類的屬性。
<%@ page contentType="text/html;charset=UTF-8" %> <%@ include file="/WEB-INF/views/include/taglib.jsp"%> <html> <head><title>用戶管理</title><meta name="decorator" content="default"/><%@include file="/WEB-INF/views/include/treeview.jsp" %><style type="text/css">.ztree {overflow:auto;margin:0;_margin-top:10px;padding:10px 0 0 10px;}</style> </head> <body><sys:message content="${message}"/><div id="content" class="row-fluid"><div id="left" class="accordion-group"><div class="accordion-heading"><a class="accordion-toggle">組織機構<i class="icon-refresh pull-right" onclick="refreshTree();"></i></a></div><div id="ztree" class="ztree"></div></div><div id="openClose" class="close"> </div><div id="right"><iframe id="officeContent" src="${ctx}/sys/user/list" width="100%" height="91%" frameborder="0"></iframe></div></div><script type="text/javascript">var setting = {data:{simpleData:{enable:true,idKey:"id",pIdKey:"pId",rootPId:'0'}},//回調函數,樹節點的點擊事件 callback:{onClick:function(event, treeId, treeNode){var id = treeNode.id == '0' ? '' :treeNode.id;$('#officeContent').attr("src","${ctx}/sys/user/list?office.id="+id+"&office.name="+treeNode.name);}}};function refreshTree(){$.getJSON("${ctx}/sys/office/treeData",function(data){$.fn.zTree.init($("#ztree"), setting, data).expandAll(true);});}refreshTree();var leftWidth = 180; // 左側窗口大小var htmlObj = $("html"), mainObj = $("#main");var frameObj = $("#left, #openClose, #right, #right iframe");function wSize(){var strs = getWindowSize().toString().split(",");htmlObj.css({"overflow-x":"hidden", "overflow-y":"hidden"});mainObj.css("width","auto");frameObj.height(strs[0] - 5);var leftWidth = ($("#left").width() < 0 ? 0 : $("#left").width());$("#right").width($("#content").width()- leftWidth - $("#openClose").width() -5);$(".ztree").width(leftWidth - 10).height(frameObj.height() - 46);}</script><script src="${ctxStatic}/common/wsize.min.js" type="text/javascript"></script> </body> </html> userIndex.jsp /*** 獲取機構JSON數據。* @param extId 排除的ID* @param type 類型(1:公司;2:部門/小組/其它:3:用戶)* @param grade 顯示級別* @param response* @return*/@RequiresPermissions("user")@ResponseBody@RequestMapping(value = "treeData")public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, @RequestParam(required=false) String type,@RequestParam(required=false) Long grade, @RequestParam(required=false) Boolean isAll, HttpServletResponse response) {List<Map<String, Object>> mapList = Lists.newArrayList();List<Office> list = officeService.findList(isAll);for (int i=0; i<list.size(); i++){Office e = list.get(i);if ((StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1))&& (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))&& (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))&& Global.YES.equals(e.getUseable())){Map<String, Object> map = Maps.newHashMap();map.put("id", e.getId());map.put("pId", e.getParentId());map.put("pIds", e.getParentIds());map.put("name", e.getName());if (type != null && "3".equals(type)){map.put("isParent", true);}mapList.add(map);}}return mapList;} }=============================================public List<Office> findList(Boolean isAll){if (isAll != null && isAll){return UserUtils.getOfficeAllList();}else{return UserUtils.getOfficeList();}}===============================/*** 獲取當前用戶有權限訪問的部門* @return*/public static List<Office> getOfficeList(){@SuppressWarnings("unchecked")List<Office> officeList = (List<Office>)getCache(CACHE_OFFICE_LIST);if (officeList == null){User user = getUser();if (user.isAdmin()){officeList = officeDao.findAllList(new Office());}else{Office office = new Office();// AND (a.id = '7' OR a.parent_ids LIKE '0,1,7,%' OR a.id IS NULL)office.getSqlMap().put("dsf", BaseService.dataScopeFilter(user, "a", ""));officeList = officeDao.findList(office);}putCache(CACHE_OFFICE_LIST, officeList);}return officeList;}/*** 獲取當前用戶有權限訪問的部門* @return*/public static List<Office> getOfficeAllList(){@SuppressWarnings("unchecked")List<Office> officeList = (List<Office>)getCache(CACHE_OFFICE_ALL_LIST);if (officeList == null){officeList = officeDao.findAllList(new Office());}return officeList;}============================================<select id="findList" resultType="Office">SELECT<include refid="officeColumns"/>FROM sys_office a<include refid="officeJoins"/>WHERE a.del_flag = #{DEL_FLAG_NORMAL}<!-- 數據范圍過濾 -->${sqlMap.dsf}OR a.id = #{currentUser.office.id}ORDER BY a.code</select> View Code?排序功能, 箭頭上下切換,在userList.jsp 中,使用了一個tag標簽實現此功能
<sys:tableSort id="orderBy" name="orderBy" value="${page.orderBy}" callback="page();"/>, orderBy作為參數把值(比如:login_name DESC)傳入sql
??? <choose>
?? ??? ??? ?<when test="page !=null and page.orderBy != null and page.orderBy != ''">
?? ??? ??? ??? ?ORDER BY ${page.orderBy}
?? ??? ??? ?</when>
?? ??? ??? ?<otherwise>
?? ??? ??? ??? ?ORDER BY c.code, o.code, a.name
?? ??? ??? ?</otherwise>
?? ??? ?</choose>
這個class 按tag規則使用<th class="sort-column login_name">登錄名</th><th class="sort-column name">姓名</th>
<%@ tag language="java" pageEncoding="UTF-8"%> <%@ include file="/WEB-INF/views/include/taglib.jsp"%> <%@ attribute name="id" type="java.lang.String" required="true"%> <%@ attribute name="name" type="java.lang.String" required="true"%> <%@ attribute name="value" type="java.lang.String" required="true"%> <%@ attribute name="callback" type="java.lang.String" required="true"%> <input id="${id}" name="${name}" type="hidden" value="${value}"/> <%-- 使用方法: 1.將本tag寫在查詢的from里;2.在需要排序th列class上添加:sort-column + 排序字段名;3.后臺sql添加排序引用page.orderBy;實例文件:userList.jsp、UserDao.xml --%> <script type="text/javascript">$(document).ready(function() {var orderBy = $("#${id}").val().split(" ");$(".sort-column").each(function(){if ($(this).hasClass(orderBy[0])){orderBy[1] = orderBy[1]&&orderBy[1].toUpperCase()=="DESC"?"down":"up";$(this).html($(this).html()+" <i class=\"icon icon-arrow-"+orderBy[1]+"\"></i>");}});$(".sort-column").click(function(){var order = $(this).attr("class").split(" ");var sort = $("#${id}").val().split(" ");for(var i=0; i<order.length; i++){if (order[i] == "sort-column"){order = order[i+1]; break;}}if (order == sort[0]){sort = (sort[1]&&sort[1].toUpperCase()=="DESC"?"ASC":"DESC");$("#${id}").val(order+" DESC"!=order+" "+sort?"":order+" "+sort);}else{$("#${id}").val(order+" ASC");}${callback}});}); </script> View Code?
Apache POI 3.9的簡單封裝,使用Annotation定義導出導入字段? ExcelExcel導入導出:http://thinkgem.iteye.com/blog/1833431
?
注意:導出字段名(默認調用當前字段的“get”方法,如指定導出字段為對象,請填寫“對象名.對象屬性”,例:“area.name”、“office.name”)
?如果是字典類型,請設置字典的type值 ,如: dictType="sys_user_type"? ,其他注解屬性看代碼內的注釋。
表單字段校驗采用的是? Hibernate Validation? :http://www.cnblogs.com/afeng7882999/p/4300032.html
在bean中注解后,在頁面對應是 (登錄名: ?class="required userName"),? ?htmlEscape="false"? 表示不進行字符轉義
?
<%@ page contentType="text/html;charset=UTF-8" %> <%@ include file="/WEB-INF/views/include/taglib.jsp"%> <html> <head><title>用戶管理</title><meta name="decorator" content="default"/><script type="text/javascript">$(document).ready(function() {$("#no").focus();$("#inputForm").validate({rules: {loginName: {remote: "${ctx}/sys/user/checkLoginName?oldLoginName=" + encodeURIComponent('${user.loginName}')}},messages: {loginName: {remote: "用戶登錄名已存在"},confirmNewPassword: {equalTo: "輸入與上面相同的密碼"}},submitHandler: function(form){loading('正在提交,請稍等...');form.submit();},errorContainer: "#messageBox",errorPlacement: function(error, element) {$("#messageBox").text("輸入有誤,請先更正。");if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){error.appendTo(element.parent().parent());} else {error.insertAfter(element);}}});});</script> </head> <body><ul class="nav nav-tabs"><li><a href="${ctx}/sys/user/list">用戶列表</a></li><li class="active"><a href="${ctx}/sys/user/form?id=${user.id}">用戶<shiro:hasPermission name="sys:user:edit">${not empty user.id?'修改':'添加'}</shiro:hasPermission><shiro:lacksPermission name="sys:user:edit">查看</shiro:lacksPermission></a></li></ul><br/><form:form id="inputForm" modelAttribute="user" action="${ctx}/sys/user/save" method="post" class="form-horizontal"><form:hidden path="id"/><sys:message content="${message}"/><div class="control-group"><label class="control-label">頭像:</label><div class="controls"><form:hidden id="nameImage" path="photo" htmlEscape="false" maxlength="255" class="input-xlarge"/><sys:ckfinder input="nameImage" type="images" uploadPath="/photo" selectMultiple="false" maxWidth="100" maxHeight="100"/></div></div><div class="control-group"><label class="control-label">歸屬公司:</label><div class="controls"><sys:treeselect id="company" name="company.id" value="${user.company.id}" labelName="company.name" labelValue="${user.company.name}"title="公司" url="/sys/office/treeData?type=1" cssClass="required"/></div></div><div class="control-group"><label class="control-label">歸屬部門:</label><div class="controls"><sys:treeselect id="office" name="office.id" value="${user.office.id}" labelName="office.name" labelValue="${user.office.name}"title="部門" url="/sys/office/treeData?type=2" cssClass="required" notAllowSelectParent="true"/></div></div><div class="control-group"><label class="control-label">工號:</label><div class="controls"><form:input path="no" htmlEscape="false" maxlength="50" class="required"/><span class="help-inline"><font color="red">*</font> </span></div></div><div class="control-group"><label class="control-label">姓名:</label><div class="controls"><form:input path="name" htmlEscape="false" maxlength="50" class="required"/><span class="help-inline"><font color="red">*</font> </span></div></div><div class="control-group"><label class="control-label">登錄名:</label><div class="controls"><input id="oldLoginName" name="oldLoginName" type="hidden" value="${user.loginName}"><form:input path="loginName" htmlEscape="false" maxlength="50" class="required userName"/><span class="help-inline"><font color="red">*</font> </span></div></div><div class="control-group"><label class="control-label">密碼:</label><div class="controls"><input id="newPassword" name="newPassword" type="password" value="" maxlength="50" minlength="3" class="${empty user.id?'required':''}"/><c:if test="${empty user.id}"><span class="help-inline"><font color="red">*</font> </span></c:if><c:if test="${not empty user.id}"><span class="help-inline">若不修改密碼,請留空。</span></c:if></div></div><div class="control-group"><label class="control-label">確認密碼:</label><div class="controls"><input id="confirmNewPassword" name="confirmNewPassword" type="password" value="" maxlength="50" minlength="3" equalTo="#newPassword"/><c:if test="${empty user.id}"><span class="help-inline"><font color="red">*</font> </span></c:if></div></div><div class="control-group"><label class="control-label">郵箱:</label><div class="controls"><form:input path="email" htmlEscape="false" maxlength="100" class="email"/></div></div><div class="control-group"><label class="control-label">電話:</label><div class="controls"><form:input path="phone" htmlEscape="false" maxlength="100"/></div></div><div class="control-group"><label class="control-label">手機:</label><div class="controls"><form:input path="mobile" htmlEscape="false" maxlength="100"/></div></div><div class="control-group"><label class="control-label">是否允許登錄:</label><div class="controls"><form:select path="loginFlag"><form:options items="${fns:getDictList('yes_no')}" itemLabel="label" itemValue="value" htmlEscape="false"/></form:select><span class="help-inline"><font color="red">*</font> “是”代表此賬號允許登錄,“否”則表示此賬號不允許登錄</span></div></div><div class="control-group"><label class="control-label">用戶類型:</label><div class="controls"><form:select path="userType" class="input-xlarge"><form:option value="" label="請選擇"/><form:options items="${fns:getDictList('sys_user_type')}" itemLabel="label" itemValue="value" htmlEscape="false"/></form:select></div></div><div class="control-group"><label class="control-label">用戶角色:</label><div class="controls"><form:checkboxes path="roleIdList" items="${allRoles}" itemLabel="name" itemValue="id" htmlEscape="false" class="required"/><span class="help-inline"><font color="red">*</font> </span></div></div><div class="control-group"><label class="control-label">備注:</label><div class="controls"><form:textarea path="remarks" htmlEscape="false" rows="3" maxlength="200" class="input-xlarge"/></div></div><c:if test="${not empty user.id}"><div class="control-group"><label class="control-label">創建時間:</label><div class="controls"><label class="lbl"><fmt:formatDate value="${user.createDate}" type="both" dateStyle="full"/></label></div></div><div class="control-group"><label class="control-label">最后登陸:</label><div class="controls"><label class="lbl">IP: ${user.loginIp} 時間:<fmt:formatDate value="${user.loginDate}" type="both" dateStyle="full"/></label></div></div></c:if><div class="form-actions"><shiro:hasPermission name="sys:user:edit"><input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存"/> </shiro:hasPermission><input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)"/></div></form:form> </body> </html> userForm.jsp?
/*** Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.*/ package com.thinkgem.jeesite.modules.sys.entity;import java.util.Date; import java.util.List;import javax.validation.constraints.NotNull;import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.Length;import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnore; import com.google.common.collect.Lists; import com.thinkgem.jeesite.common.config.Global; import com.thinkgem.jeesite.common.persistence.DataEntity; import com.thinkgem.jeesite.common.supcan.annotation.treelist.cols.SupCol; import com.thinkgem.jeesite.common.utils.Collections3; import com.thinkgem.jeesite.common.utils.excel.annotation.ExcelField; import com.thinkgem.jeesite.common.utils.excel.fieldtype.RoleListType;/*** 用戶Entity* @author ThinkGem* @version 2013-12-05*/ public class User extends DataEntity<User> {private static final long serialVersionUID = 1L;private Office company; // 歸屬公司private Office office; // 歸屬部門private String loginName;// 登錄名private String password;// 密碼private String no; // 工號private String name; // 姓名private String email; // 郵箱private String phone; // 電話private String mobile; // 手機private String userType;// 用戶類型private String loginIp; // 最后登陸IPprivate Date loginDate; // 最后登陸日期private String loginFlag; // 是否允許登陸private String photo; // 頭像private String oldLoginName;// 原登錄名private String newPassword; // 新密碼private String oldLoginIp; // 上次登陸IPprivate Date oldLoginDate; // 上次登陸日期private Role role; // 根據角色查詢用戶條件private List<Role> roleList = Lists.newArrayList(); // 擁有角色列表public User() {super();this.loginFlag = Global.YES;}public User(String id){super(id);}public User(String id, String loginName){super(id);this.loginName = loginName;}public User(Role role){super();this.role = role;}public String getPhoto() {return photo;}public void setPhoto(String photo) {this.photo = photo;}public String getLoginFlag() {return loginFlag;}public void setLoginFlag(String loginFlag) {this.loginFlag = loginFlag;}@SupCol(isUnique="true", isHide="true")@ExcelField(title="ID", type=1, align=2, sort=1)public String getId() {return id;}@JsonIgnore@NotNull(message="歸屬公司不能為空")@ExcelField(title="歸屬公司", align=2, sort=20)public Office getCompany() {return company;}public void setCompany(Office company) {this.company = company;}@JsonIgnore@NotNull(message="歸屬部門不能為空")@ExcelField(title="歸屬部門", align=2, sort=25)public Office getOffice() {return office;}public void setOffice(Office office) {this.office = office;}@Length(min=1, max=100, message="登錄名長度必須介于 1 和 100 之間")@ExcelField(title="登錄名", align=2, sort=30)public String getLoginName() {return loginName;}public void setLoginName(String loginName) {this.loginName = loginName;}@JsonIgnore@Length(min=1, max=100, message="密碼長度必須介于 1 和 100 之間")public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Length(min=1, max=100, message="姓名長度必須介于 1 和 100 之間")@ExcelField(title="姓名", align=2, sort=40)public String getName() {return name;}@Length(min=1, max=100, message="工號長度必須介于 1 和 100 之間")@ExcelField(title="工號", align=2, sort=45)public String getNo() {return no;}public void setNo(String no) {this.no = no;}public void setName(String name) {this.name = name;}@Email(message="郵箱格式不正確")@Length(min=0, max=200, message="郵箱長度必須介于 1 和 200 之間")@ExcelField(title="郵箱", align=1, sort=50)public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}@Length(min=0, max=200, message="電話長度必須介于 1 和 200 之間")@ExcelField(title="電話", align=2, sort=60)public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}@Length(min=0, max=200, message="手機長度必須介于 1 和 200 之間")@ExcelField(title="手機", align=2, sort=70)public String getMobile() {return mobile;}public void setMobile(String mobile) {this.mobile = mobile;}@ExcelField(title="備注", align=1, sort=900)public String getRemarks() {return remarks;}@Length(min=0, max=100, message="用戶類型長度必須介于 1 和 100 之間")@ExcelField(title="用戶類型", align=2, sort=80, dictType="sys_user_type")public String getUserType() {return userType;}public void setUserType(String userType) {this.userType = userType;}@ExcelField(title="創建時間", type=0, align=1, sort=90)public Date getCreateDate() {return createDate;}@ExcelField(title="最后登錄IP", type=1, align=1, sort=100)public String getLoginIp() {return loginIp;}public void setLoginIp(String loginIp) {this.loginIp = loginIp;}@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")@ExcelField(title="最后登錄日期", type=1, align=1, sort=110)public Date getLoginDate() {return loginDate;}public void setLoginDate(Date loginDate) {this.loginDate = loginDate;}public String getOldLoginName() {return oldLoginName;}public void setOldLoginName(String oldLoginName) {this.oldLoginName = oldLoginName;}public String getNewPassword() {return newPassword;}public void setNewPassword(String newPassword) {this.newPassword = newPassword;}public String getOldLoginIp() {if (oldLoginIp == null){return loginIp;}return oldLoginIp;}public void setOldLoginIp(String oldLoginIp) {this.oldLoginIp = oldLoginIp;}@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")public Date getOldLoginDate() {if (oldLoginDate == null){return loginDate;}return oldLoginDate;}public void setOldLoginDate(Date oldLoginDate) {this.oldLoginDate = oldLoginDate;}public Role getRole() {return role;}public void setRole(Role role) {this.role = role;}@JsonIgnore@ExcelField(title="擁有角色", align=1, sort=800, fieldType=RoleListType.class)public List<Role> getRoleList() {return roleList;}public void setRoleList(List<Role> roleList) {this.roleList = roleList;}@JsonIgnorepublic List<String> getRoleIdList() {List<String> roleIdList = Lists.newArrayList();for (Role role : roleList) {roleIdList.add(role.getId());}return roleIdList;}public void setRoleIdList(List<String> roleIdList) {roleList = Lists.newArrayList();for (String roleId : roleIdList) {Role role = new Role();role.setId(roleId);roleList.add(role);}}/*** 用戶擁有的角色名稱字符串, 多個角色名稱用','分隔.*/public String getRoleNames() {return Collections3.extractToString(roleList, "name", ",");}public boolean isAdmin(){return isAdmin(this.id);}public static boolean isAdmin(String id){return id != null && "1".equals(id);}@Overridepublic String toString() {return id;} } View Code?數據導入導出封裝的比較好,貼個導入的方法,以前自己寫的太差了,校驗都是自己寫,重復造輪子。
return "redirect:" + adminPath + "/sys/user/list?repage";? //傳遞 repage 參數,來記住頁碼,參考Page.java
/*** 導入用戶數據* @param file* @param redirectAttributes* @return*/@RequiresPermissions("sys:user:edit")@RequestMapping(value = "import", method=RequestMethod.POST)public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {if(Global.isDemoMode()){addMessage(redirectAttributes, "演示模式,不允許操作!");return "redirect:" + adminPath + "/sys/user/list?repage";}try {int successNum = 0;int failureNum = 0;StringBuilder failureMsg = new StringBuilder();ImportExcel ei = new ImportExcel(file, 1, 0);List<User> list = ei.getDataList(User.class);for (User user : list){try{if ("true".equals(checkLoginName("", user.getLoginName()))){//檢驗用戶名是否重復user.setPassword(SystemService.entryptPassword("123456"));BeanValidators.validateWithException(validator, user); //JSR303 Validator(Hibernate Validator)工具類校驗字段,不符合注解拋出異常 systemService.saveUser(user);successNum++;}else{failureMsg.append("<br/>登錄名 "+user.getLoginName()+" 已存在; ");failureNum++;}}catch(ConstraintViolationException ex){failureMsg.append("<br/>登錄名 "+user.getLoginName()+" 導入失敗:");List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");for (String message : messageList){failureMsg.append(message+"; ");failureNum++;}}catch (Exception ex) {failureMsg.append("<br/>登錄名 "+user.getLoginName()+" 導入失敗:"+ex.getMessage());}}if (failureNum>0){failureMsg.insert(0, ",失敗 "+failureNum+" 條用戶,導入信息如下:");}addMessage(redirectAttributes, "已成功導入 "+successNum+" 條用戶"+failureMsg);} catch (Exception e) {addMessage(redirectAttributes, "導入用戶失敗!失敗信息:"+e.getMessage());}return "redirect:" + adminPath + "/sys/user/list?repage"; //傳遞 repage 參數,來記住頁碼,參考Page.java} View Code
?
轉載于:https://www.cnblogs.com/skyislimit/p/6741955.html
總結
以上是生活随笔為你收集整理的【JeeSite】用户管理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 循序渐进学Python2变量与输入
- 下一篇: 利用事件冒泡实现简单的网页计算器