HI All,
I have three tables tbl_category, tbl_subcategory, tbl_product . where categoryid is foreign key in subcategory table and subcategoryid is foreign key in prduct table. I want to show category and subcategory on home page menubar. I just reach upto display category on menubar but not able to get subcategory on mouseover of particular menu.

So I have a servlet to retrive data and jsp to display it.and jsp code is as below which can show only category.

<ul>
                <% Iterator itr;%>
               <% List data=(List)request.getAttribute("data");
                    for(itr=data.iterator(); itr.hasNext(); ){
                %>
                <li><a href=""><%=itr.next()%></a></li>
                <%}%>
                </ul>



can you please help me to show subcategory on mouseover

Dani AI

Generated

A simple, robust approach is to send a hierarchical menu from the servlet to the JSP and render it with JSTL/EL (avoid scriptlets). Build a model where each Category has a List of Subcategory objects (or a LinkedHashMap preserving order). You can either (A) fetch categories and subcategories in one LEFT JOIN, or (B) fetch categories first and subcategories in a second query. Option (A) is usually simpler and faster for a single menu load.

Example SQL (one-query approach):

SELECT c.id AS cat_id, c.name AS cat_name,
       s.id AS sub_id, s.name AS sub_name
FROM category c
LEFT JOIN subcategory s ON s.category_id = c.id
ORDER BY c.name, s.name;

Server-side: iterate the ordered ResultSet and assemble a List<Category> (create a new Category only when the category id changes; append subcategories to its list). Put that List as a request attribute, e.g. request.setAttribute("categories", categories); and forward to the JSP.

JSP (JSTL/EL) pattern to render nested <ul>/<li>:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<ul class="menu">
  <c:forEach var="cat" items="${categories}">
    <li>
      ${cat.name}
      <c:if test="${not empty cat.subcategories}">
        <ul class="submenu">
          <c:forEach var="sub" items="${cat.subcategories}">
            <li><a href="products.jsp?sub=${sub.id}">${sub.name}</a></li>
          </c:forEach>
        </ul>
      </c:if>
    </li>
  </c:forEach>
</ul>

Minimal CSS for mouseover submenu:

.menu, .menu ul { list-style:none; margin:0; padding:0; }
.menu .submenu { display:none; position:absolute; }
.menu li:hover > .submenu { display:block; }

Quick troubleshooting notes: remove the extra call you make after forwarding (do not call another response writer or processRequest after RequestDispatcher.forward), use PreparedStatement and try-with-resources (or a pool), and avoid printing HTML from the servlet. As observed, this belongs in the JSP/Servlet area; implementing the hierarchical model + JSTL will produce the desired mouseover submenus for .

Recommended Answers

All 4 Replies

May be u shud post this code under jsp section....

in this section we can help u with queries

Here is my servlet code

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Category extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Category</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet Category at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }catch(ClassNotFoundException cne){
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();
        ArrayList list=new ArrayList();
        try{
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/store?user=shilpa&password=password");
            String query="select category_id,category_name from tbl_category";
            Statement st1=con.createStatement();
            ResultSet rs=st1.executeQuery(query);
            while (rs.next()) {
                //list.add(rs.getInt("category_id"));
                list.add(rs.getString("category_name"));          
             }
            request.setAttribute("data",list);
          RequestDispatcher rd=request.getRequestDispatcher("category.jsp");
          rd.forward(request, response);
        processRequest(request, response);
        }catch(Exception e){

        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

Here is jsp code

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page language="java" import="java.util.*" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
             <ul>
                  <% Iterator itr;%>
                  <% List data=(List)request.getAttribute("data");
                     for(itr=data.iterator(); itr.hasNext(); ){
                   %>
                   <li><a href=""><%=itr.next()%></a></li>
              <%}%>
             </ul>

                <%}%>
          </body>
</html>

Which shows result category name from category table only but I want subcategory too on mouseover...
Thank you

This is VB.net section.... Servlet comes in Java....
This is not the correct section to post the code dear.....

so can I change tags ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.