一、頁面查詢功能帶分頁
後端代碼:javascript
/** * @Author Mc * @Description: 根據條件查詢角色列表信息 * @Date 2018/4/19 10:49 */ @Override public Response<Paging<BvsRole>> findListPage(BvsRole bvsRole){ try { // 調用PageHelper封裝方法設置其實分頁(攔截器) PageHelper.startPage(bvsRole.getPageNo(),bvsRole.getPageSize()); // 查詢角色數據 List<BvsRole> bvsRoles = bvsRoleDao.findList(bvsRole); // 因重名,故全名引入 com.github.pagehelper.PageInfo pageInfo = com.github.pagehelper.PageInfo.of(bvsRoles); // 轉化爲本身的paging對象,此方法可重寫 Paging<BvsRole> paging = new Paging(pageInfo.getTotal(), bvsRoles); // 檢查狀態 checkState(!Arguments.isNullOrEmpty(bvsRoles),"find.bvsRole.by.bvsRole.is.null"); return Response.ok(paging); } catch (NullPointerException | IllegalStateException e) { log.error("find by key fail bvsRole: {}, cause: {}", bvsRole, getStackTraceAsString(e)); return Response.fail(e.getMessage()); } catch (Exception e) { log.error("find by key fail bvsRole: {}, cause: {}", bvsRole, getStackTraceAsString(e)); return Response.fail("find.bvsRole.by.bvsRole.fail"); } }
前端代碼:前端
// JS頁面 // post 請求發送對象 export function post(api, params = null) { return request .post(api) .send(params) .then(response => checkData(response), error => errorCatch(error)); } // 查詢用戶角色 export function getRoles(params) { return (dispatch) => { dispatch(receiveInit()); return post('/api/bvsRole/bvsRoleListPage', params==undefined?{}:params).then((data) => { dispatch(receiveBvsRoles(data)); }, () => { dispatch(receiveErrors()); }); }; } //jsx頁面 // 分頁 const PAGE = { current: 1, pageSize: 10, showSizeChanger: true, showQuickJumper: true, }; // 分頁事件 handleTableChange(pagination) { const { current, pageSize } = pagination; const { form, query } = this.props; const fieldsValues = form.getFieldsValue(); query({ pageNo: current, pageSize, ...fieldsValues, }); this.setState({ pagination: { current, pageSize, }, }); } <Table columns={columns} dataSource={bvsRoles.data} loading={bvsRoles.fetching} pagination={pagination} onChange={ (paginations) => { this.handleTableChange(paginations); } } />
二、鑽取方法獲取樹列表功能
後端代碼:java
package net.haier.bvs.pub.util; import io.terminus.common.model.Response; import io.terminus.common.utils.Arguments; import lombok.extern.slf4j.Slf4j; import net.haier.bvs.pub.model.TreeNode; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Throwables.getStackTraceAsString; @Slf4j public class TreeUtil { private static final String TREEID = "getTreeId"; private static final String TREENAME = "getTreeName"; private static final String PARENTID = "getParentId"; /** * @Author Mc * @Description: 經過樹列表 * @Date 2018/5/14 15:29 * @param roots 根級數據 * @param allData 全部數據 */ public static <T> Response<List<TreeNode>> getTree(List<T> roots , List<T> allData){ List<TreeNode> nodes = new ArrayList<TreeNode>(); try { // 選中樹節點時不返回任何數據 // if(!"0".equals(this.id)) return null; // 構建樹結構 LinkedList<T> list = listToLinkedList(allData); // 循環尋找子節點 roots.forEach(t -> { TreeNode treeNode = buildNode(t); buildTree(list, treeNode); nodes.add(treeNode); }); // 校驗返回值 checkState(!Arguments.isNullOrEmpty(nodes),"find.nodes.by.nodes.is.null"); return Response.ok(nodes); } catch (NullPointerException | IllegalStateException e) { log.error("find by key fail nodes: {}, cause: {}", nodes, getStackTraceAsString(e)); return Response.fail(e.getMessage()); } catch (Exception e) { log.error("find by key fail nodes: {}, cause: {}", nodes, getStackTraceAsString(e)); return Response.fail("find.nodes.by.nodes.fail"); } } /** * @Author Mc * @Description: listToLinkedList * @Date 2018/5/5 16:08 */ private static <T> LinkedList<T> listToLinkedList(List<T> allData){ if(allData instanceof LinkedList) return (LinkedList<T>)allData; LinkedList<T> result = new LinkedList<T>(); allData.forEach( r -> result.add(r)); return result; } /** * @Author Mc * @Description: 建立TreeNode對象 * @Date 2018/5/5 17:54 */ private static <T> TreeNode buildNode(T t) { // 樹對象的建立 TreeNode treeNode = new TreeNode(); try { // 獲取泛型T的Class對象,反向的調用get方法,獲取數據 Class listClass = t.getClass(); // 獲取get()方法 Method treeId = listClass.getMethod(TREEID); Method treeName = listClass.getMethod(TREENAME); // 調用get()方法 treeNode.setKey(treeId.invoke(t) != null ? treeId.invoke(t).toString() : null); treeNode.setTitle(treeName.invoke(t) != null ? treeName.invoke(t).toString() : null); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { e.printStackTrace(); log.error("find by key fail treeNode: {}, cause: {}", treeNode, getStackTraceAsString(e)); } return treeNode; } /** * @Author Mc * @Description: 構建資源樹 * @Date 2018/5/4 17:57 */ private static <T> void buildTree(LinkedList<T> allDate,TreeNode parentNode){ if(allDate.isEmpty() || parentNode == null) return; Collection<TreeNode> children = parentNode.getChildren(); if(children == null) parentNode.setChildren(new ArrayList<TreeNode>()); Long parentNodeId = Long.valueOf(parentNode.getKey()); try { // 獲取泛型T的Class對象,反向的調用get方法,獲取數據 Class listClass = allDate.getFirst().getClass(); // 獲取get()方法 Method treeId = listClass.getMethod(TREEID); Method parentId = listClass.getMethod(PARENTID); // 調用get()方法 allDate.forEach((T r) ->{ // 設置該資源的直接子元素-剔除自身 try { if(parentNodeId.equals(parentId.invoke(r) != null ? Long.valueOf(parentId.invoke(r).toString()) : null) && !parentNodeId.equals(treeId.invoke(r)!= null ? Long.valueOf(treeId.invoke(r).toString()) : null)){ TreeNode treeNode = buildNode(r); parentNode.getChildren().add(treeNode); } // 從列表中刪除父節點 if(parentNodeId.equals(treeId.invoke(r) != null ? Long.valueOf(treeId.invoke(r).toString()) : null)){ r = (T) new LinkedList<T>(); return; } } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } }); } catch (NoSuchMethodException e) { e.printStackTrace(); } // 對子節點遍歷 parentNode.getChildren().forEach(c->buildTree(allDate,c)); } }
前端代碼:node
js:git
// 查詢資源 export function findResource() { return (dispatch) => { dispatch(receiveInit()); post('/api/resourceInfo/resourceTree',{}).then((data) => { dispatch(receiveResourceTree(data)); }, () => { dispatch(receiveErrors()); }); }; } // 賦值資源樹數據 export function receiveResourceTree(treeDate) { return { type: RECEIVE_ADDROLE, payload: { fetching: false, treeDate, }, }; }
jsx:github
import { Tree } from 'antd'; const TreeNode = Tree.TreeNode; // 展開樹事件 onExpand = (expandedKeys) => { console.log('onExpand', arguments); this.setState({ expandedKeys, autoExpandParent: false, }); } // 勾選樹事件 onCheck = (checkedKeys) => { console.log('onCheck', checkedKeys); this.setState({ checkedKeys }); } // 選擇樹事件 onSelect = (selectedKeys, info) => { console.log('onSelect', info); this.setState({ selectedKeys }); } // 數據加載事件 renderTreeNodes = (data) => { return data.map((item) => { if (item.children) { return ( <TreeNode title={item.title} key={item.key} dataRef={item}> {this.renderTreeNodes(item.children)} </TreeNode> ); } return <TreeNode {...item} />; }); } <Row> {addRole.treeDate.length ? <Tree checkable onExpand={this.onExpand} expandedKeys={this.state.expandedKeys} autoExpandParent={this.state.autoExpandParent} onCheck={this.onCheck} checkedKeys={this.state.checkedKeys} onSelect={this.onSelect} selectedKeys={this.state.selectedKeys} > {this.renderTreeNodes(addRole.treeDate)} </Tree> : 'loading tree'} </Row>
三、新增&編輯功能
後端代碼:後端
/** * @Author Mc * @Description: 新增角色功能 * @Date 2018/4/19 16:06 */ @Override public Response<Boolean> saveBvsRole(BvsRole bvsRole) { try { boolean success = false; // 根據isNewRcord和id判斷新增仍是修改 if(bvsRole.getId() == null || bvsRole.getIsNewRecord()){ // 新增操做 bvsRole.setId(bvsRoleDao.getRoleId()); bvsRole.setGmtCreate(new Date()); bvsRole.setGmtModified(new Date()); checkNotNull(bvsRole, "bvsRole.is.empty"); success = bvsRoleDao.create(bvsRole); // 新增RoleResource表數據 bvsRoleDao.createRoleResource(bvsRole); }else{ // 編輯操做 bvsRole.setGmtModified(new Date()); success = bvsRoleDao.update(bvsRole); // 編輯下先所有刪除RoleResource表數據 bvsRoleDao.deleteRoleResource(bvsRole.getId()); // 而後新增RoleResource表數據 bvsRoleDao.createRoleResource(bvsRole); } checkState(success, "create.bvsRole.fail"); return Response.ok(Boolean.TRUE); } catch (NullPointerException e) { log.error("failed to create bvsRole({}) , caused: {}", bvsRole, getStackTraceAsString(e)); return Response.fail(e.getMessage()); } catch (Exception e) { log.error("failed to create bvsRole({}) , caused: {}", bvsRole, getStackTraceAsString(e)); return Response.fail("create.role.fail"); }
前端代碼:api
// 新增角色 js頁面 export function createRole(param) { return (dispatch) => { dispatch(receiveInit()); return post('/api/bvsRole/saveBvsRole', param).then((data) => { dispatch(receiveAddroles({data})); return Promise.resolve(data); }, () => { dispatch(receiveErrors()); return Promise.reject(null); }); }; } // jsx頁面 // 新增頁面跳轉 handleAdd(e) { e.preventDefault(); browserHistory.push('/addRole'); } // 編輯事件 editRole(e, id) { e.preventDefault(); browserHistory.push(`/addRole?id=${id}&isNewRecord=false`); } componentWillMount (){ const { location,resource,findById } = this.props; // 若是編輯的話查詢數據 if(location.query.isNewRecord === "false"){ // 賦值路由傳值 this.setState({ isNewRecord: location.query.isNewRecord, id: location.query.id, }); // 執行完findById後能獲取到數據 findById(location.query).then( () => { const {addRole, form } = this.props; form.setFieldsValue(addRole.bvsRole); this.setState({ checkedKeys: addRole.checkTree, expandedKeys: addRole.checkTree, });} ); } // 調用樹資源方法 resource(); } // 提交方法 handleSubmit(e) { e.preventDefault(); const { form, createRole } = this.props; form.validateFields((err, values) => { if (err) { return; }else{ const fieldsValues = form.getFieldsValue(); const values = { ...fieldsValues, createBy:'mc', lastModifiedBy:'mc', pageNo: PAGE.current, pageSize: PAGE.pageSize, pagingFlag : 0, checkedKeys: this.state.checkedKeys, isNewRecord: this.state.isNewRecord, id: this.state.id, }; this.props.createRole(values).then((msg) => { if (msg && msg.success == true) { notification.success({ message: '操做成功', description: `${values.isNewRecord == true ? '新增' : '編輯'}角色成功!`, }); browserHistory.goBack(); }else{ notification.error({ message: '操做失敗', description: `${values.isNewRecord == true ? '新增' : '編輯'}角色失敗!`, }); } }); } }); this.setState({ pagination: { ...PAGE, }, }); }
歡迎指正錯誤!antd