springboot使用遞歸獲取導(dǎo)航無(wú)限級(jí)分類,使用thymeleaf渲染導(dǎo)航欄,在實(shí)際項(xiàng)目中經(jīng)常會(huì)出現(xiàn)三級(jí)分類或者多級(jí)分類的情況,一般采用存pid的方式存儲(chǔ),在去數(shù)據(jù)時(shí)遞歸迭代下數(shù)據(jù)就行來(lái)看看導(dǎo)航欄遞歸實(shí)現(xiàn)吧!
項(xiàng)目的源代碼:碼云下載
由于更新的數(shù)據(jù)庫(kù)字段和插入了部分?jǐn)?shù)據(jù),需要重新執(zhí)行下碼云的sql語(yǔ)句,同時(shí)重命名了文件夾mapper為dao.
1. 實(shí)體類增加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增加遞歸格式化分類函數(shù)unlimitedTree
,格式成帶children層級(jí)
@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渲染顯示數(shù)據(jù)
<nav>
<ul id="starlist">
<li><a href="index.html" title="首頁(yè)">網(wǎng)站首頁(yè)</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">個(gè)人博客</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>
部分代碼未完全貼出來(lái),詳細(xì)代碼參考碼云倉(cāng)庫(kù)代碼!