1、页面查询功能带分页
后端代码:
/**
* @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);
}
}
/>
2、钻取方法获取树列表功能
后端代码:
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));
}
}
前端代码:
js:
// 查询资源
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:
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>
3、新增&编辑功能
后端代码:
/**
* @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");
}
前端代码:
// 新增角色 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,
},
});
}
欢迎指正错误!