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.
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.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 { Class.forName("com.mysql.jdbc.Driver"); 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); if(resultSet0.next()){ if(resultSet0.getInt(1)==0) { return; } } menuTreeString=menuTreeString+"\n<ul>\n"; ResultSet resultSet = con.createStatement().executeQuery("select * from menu_items where parent="+parentMenuId); while(resultSet.next()){ menuTreeString=menuTreeString+"\n<li><a href=\"#\">"+resultSet.getString(2)+"</a>"; int currentMenuId=resultSet.getInt(1); createMenuItem(currentMenuId); menuTreeString=menuTreeString+"</li>"; } intendation=intendation+"\t"; menuTreeString=menuTreeString+"\n</ul>\n"; } public static void main(String[] args) throws ClassNotFoundException, SQLException { CreateMenuTree c=new CreateMenuTree(); c.createMenuItem(0); System.out.println(c.menuTreeString); } }
Comments