springboot使用递归获取导航无限级分类 使用thymel
2020-05-12 本文已影响0人
思议岁月
springboot使用递归获取导航无限级分类,使用thymeleaf渲染导航栏,在实际项目中经常会出现三级分类或者多级分类的情况,一般采用存pid的方式存储,在去数据时递归迭代下数据就行来看看导航栏递归实现吧!
项目的源代码:码云下载
由于更新的数据库字段和插入了部分数据,需要重新执行下码云的sql语句,同时重命名了文件夹mapper为dao.
1. 实体类增加children
public class Nav {
private Integer id;
private String title;
private String url;
private Integer sorts;
private Integer pid;
private Date createTime;
private Date updateTime;
private Boolean status;
private List<Nav> children;
2. NavServiceImpl增加递归格式化分类函数unlimitedTree
,格式成带children层级
@Service
public class NavServiceImpl implements NavService {
@Resource
private NavDao navDao;
@Override
public int deleteByPrimaryKey(Integer id) {
return 0;
}
@Override
public int insert(Nav record) {
return 0;
}
@Override
public Nav selectByPrimaryKey(Integer id) {
return null;
}
@Override
public List<Nav> selectAll() {
List<Nav> navs = navDao.selectAll();
return unlimitedTree(navs, 0);
}
@Override
public int updateByPrimaryKey(Nav record) {
return 0;
}
public static List<Nav> formatNavs(List<Nav> navs,List<Nav> navs_list,Integer pid) {
for (Nav nav:navs){
navs_list.add(nav);
List<Nav> childrenNavs=nav.getChildren();
if(null!=childrenNavs){
navs_list=formatNavs(childrenNavs,navs_list,nav.getPid());
}
}
return navs_list;
}
public static List<Nav> unlimitedTree(List<Nav> navs,Integer pid) {
ArrayList<Nav> navs_list =new ArrayList<>();
for (Nav nav:navs){
if(pid==nav.getPid()){
nav.setChildren(unlimitedTree(navs,nav.getId()));
navs_list.add(nav);
}
}
return navs_list;
}
}
3.IndexController查询出值
@Controller
public class IndexController {
@Resource
private NavService nav;
@GetMapping("/")
public String index(Model m) {
List<Nav> navs = nav.selectAll();
m.addAttribute("navs",navs);
return "index";
}
}
4.使用thymeleaf渲染显示数据
<nav>
<ul id="starlist">
<li><a href="index.html" title="首页">网站首页</a></li>
<li th:each="nav : ${navs}" th:class="${not #lists.isEmpty(nav.children)}?'menu'">
<a th:href="@{${nav.url}}" th:text="${nav.title}" href="index1.html">个人博客</a>
<ul th:if="${not #lists.isEmpty(nav.children)}" class="sub">
<li th:each="children : ${nav.children}">
<a th:href="@{${children.url}}" th:text="${children.title}" href="index1.html">CSS3|Html5</a>
</li>
</ul>
</li>
</ul>
</nav>
部分代码未完全贴出来,详细代码参考码云仓库代码!