Generating Menu Tree Or Catagory Tree hierarchy

There has always been a basic requirements in website or web applications that the menu bar must be dynamic and all menu items should be appeared under their respected parent. Here, if you are managing the menu items in database, then you have to retrieve all menu items in the way that each menu item must have its proper position in menu tree. here you could use just a loop because you don't know that how many menu times are going to be added in future.

So, Here is the example in which I am using the recursion approach for creating the menu tree dynamically for any level. there is the database table "menu_items" having the columns id, name and parent. Parent column will have the id of the parent menu as foreign key.

You can increase some more columns as per your requirements like label, url and so on. There are some values already there for testing purpose.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class CreateMenuTree {
 Connection con = null;

 String menuTreeString="";
 String intendation="\t";
 CreateMenuTree() throws ClassNotFoundException, SQLException {
  con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
 public void createMenuItem(int parentMenuId) throws SQLException{
  ResultSet resultSet0 = con.createStatement().executeQuery("select count(*) from menu_items where parent="+parentMenuId);
  ResultSet resultSet = con.createStatement().executeQuery("select * from menu_items where parent="+parentMenuId);
   menuTreeString=menuTreeString+"\n<li><a href=\"#\">"+resultSet.getString(2)+"</a>";
   int currentMenuId=resultSet.getInt(1);
 public static void main(String[] args) throws ClassNotFoundException, SQLException {
  CreateMenuTree c=new CreateMenuTree();

The above code is working to generate the menu tree. It will generate HTML structure for the menu tree i.e. ul and li based tree structure.

Popular Posts