无限树级菜单的兑现
<s:select>无限树级菜单的实现
最近在做一个公安的项目,因为部门比较多,并且存在无限级的子部门,子子部门…………,所以在显示部门的时候要求以无限树级的形式来显示这个部门的信息。在数据库设计的时候有个部门表,部门表里面有个parentId的字段来说明部门和子部门的关系。需求摆在这,绞尽脑汁,终于想出来了使用递归的方式来实现了,下面是自己递归封装list的代码,与大家共享:
public List<GroupInfo> listGroupInfo(int compyId,int type,User user){ DBConn db = null; List<GroupInfo> groupInfos= new ArrayList<GroupInfo>(); try{ db = new DBConn(); String strSQL = "select * from groupInfo where compyId="+compyId+" and type="+type+" and ParentId=0"; if(user.getGrade()>0){ strSQL = strSQL+" and groupId="+user.getGroup().getGroupId()+""; } ResultSet rs = db.OpenSql(strSQL); String str = "—"; while(rs.next()){ GroupInfo groupInfo = new GroupInfo(); groupInfo.setGroupId(rs.getInt("groupId")); groupInfo.setGroupName(str+rs.getString("groupName")); groupInfo.setMemo(rs.getString("memo")); groupInfo.setType(rs.getInt("type")); groupInfos.add(groupInfo); //递归调用 groupInfos.addAll(goback(compyId,type,rs.getInt("groupId"),db,str)) ; } logger.info("list groupInfo by compyId success!compyId="+compyId+",type="+type); } catch (Exception e) { logger.error("list groupInfo by compyId failed!compyId="+compyId+",type="+type,e); System.out.println(e); } finally { db.close(); } return groupInfos; } public List<GroupInfo> goback(int companyId,int type,int groupId,DBConn db,String str){ String strSQL9 = "select * from groupInfo where compyId="+companyId+" and type="+type+" and ParentId=?"; List<GroupInfo> list = new ArrayList<GroupInfo>(); PreparedStatement pst=null; try { pst = db.getConn().prepareStatement(strSQL9); pst.setInt(1, groupId); ResultSet rs8 = pst.executeQuery(); while(rs8.next()){ GroupInfo groupInfo = new GroupInfo(); str = str + "—"; groupInfo.setGroupId(rs8.getInt("groupId")); groupInfo.setGroupName(str+rs8.getString("groupName")); groupInfo.setMemo(rs8.getString("memo")); groupInfo.setType(rs8.getInt("type")); list.add(groupInfo); //递归调用 list.addAll(goback(companyId,type,rs8.getInt("groupId"),db,str)); logger.info("list groupInfo by compyId success!递归成功!compyId="+companyId+",type="+type); } } catch (SQLException e) { // TNODO Auto-generated catch block e.printStackTrace(); } return list; }
前台显示的就是就是一个<s:select>标签。
这里面就是使用了递归来实现的无限级的树形菜单。