Tree组件实现
前言
这篇文章是继上篇文章的后续,
easyui的入门以及tree组件的后端
现在说一下如何在前端实现
在前端实现tree组件
首先先看一下效果:
导入依赖jar包
继上次的代码之后,在PermissionDao中添加一个能够将数据库中的数据体现出父子结构的方法
public List<TreeVo<Permission>> topNode(Permission permission,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
List<Permission> list = this.list(permission, pageBean);
// 通过工具类完成指定格式的输出
List<TreeVo<Permission>> nodes = new ArrayList<TreeVo<Permission>>();
// Permission的格式不满足easyui的tree组件的展现的数据格式
TreeVo treeVo = null;
for (Permission p : list) {
treeVo = new TreeVo<>();
treeVo.setId(p.getId()+"");
treeVo.setText(p.getName());
treeVo.setParentId(p.getPid()+"");
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("self", p);
treeVo.setAttributes(attributes);
nodes.add(treeVo);
}
// return BuildTree.build(nodes);
return BuildTree.buildList(nodes, "0");
}
然后通过自定义mvc完成PermissionAction类
public class PermissionAction extends ActionSupport implements ModelDriven<Permission>{
private Permission permission = new Permission();
private PermissionDao permissionDao = new PermissionDao();
@Override
public Permission getModel() {
return permission;
}
public String menuTree(HttpServletRequest req,HttpServletResponse resp) {
try {
ResponseUtil.writeJson(resp, this.permissionDao.topNode(null, null));
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 结果码的位置为了在config.xml中寻找是转发还是重定向
return null;
}
}
ResponseUtil将传过来的对象转换为json格式的字符串
public class ResponseUtil {
public static void write(HttpServletResponse response,Object o)throws Exception{
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println(o.toString());
out.flush();
out.close();
}
public static void writeJson(HttpServletResponse response,Object o)throws Exception{
response.setContentType("text/html;charset=utf-8");
ObjectMapper om = new ObjectMapper();
String jsonstr = om.writeValueAsString(o);
PrintWriter out=response.getWriter();
out.println(jsonstr.toString());
out.flush();
out.close();
}
}
然后在mvc.xml中配置一下
<config>
<action path="/permission" type="com.dailang.web.PermissionAction">
</action>
</config>
index.js
$(function(){
$('#tt').tree({
url:$("#dl").val()+'/permission.action?methodName=menuTree'
});
})
就能出现我们想要的结果
最后说一下如果出现问题解决的思路
解决问题的思路
首先需要判断是前端还是后端的错误
前端:
F12查看请求
1、如果是浏览器缓存问题的话,Ctrl+Shift+Delete清除缓存之后再访问
2、js代码中的地址出现错误
后端:
1、根据经验找到对应的方法打上断点,看方法是否会执行,如果没有找到方法就看路径问题,修改后继续排查问题
2、查看控制台错误分析