如何使用 Javaee jsp servlet jpa jstl ejb 在添加产品页面上显示类别下拉列表?

How to show category dropdown on add product page in using Javaee jsp servlet jpa jstl ejb?

我一直在关注ecommerce tutorial from Netbeans . This tutorial however lacks many real world services and one of them is inserting new products so i tried to implement it on my own however i am having problem to display categories on select's options dynamically on addProduct.jsp i created. Surprisingly it shows up when i put that in index.jsp on admin folder. Also uploaded this on youtube

这是我的 AdminServlet

package controller;
import entity.Category;
import entity.Customer;
import entity.CustomerOrder;
//import entity.Product;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.ServletSecurity.TransportGuarantee;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import session.CategoryFacade;
//import session.ProductFacade;
import session.CategoryManager;
import session.ProductManager;
import session.CustomerFacade;
import session.CustomerOrderFacade;
import session.OrderManager;
import validate.Validator;

/**
 *
 * @author Admin
 */
@WebServlet(name = "AdminServlet", 
            loadOnStartup = 2,
            urlPatterns = {
                            "/admin/",
                            "/admin/viewOrders",
                            "/admin/viewCustomers",
                            "/admin/customerRecord",
                            //"/admin/customerOrder",
                            "/admin/orderRecord",

                            "/admin/logout",
                            "/admin/showCategory",
                            "/admin/addCategory",
                            "/admin/addCategory.jsp",
                            "/admin/addProduct",
                            "/admin/addProduct.jsp"

                            })
@ServletSecurity( @HttpConstraint(transportGuarantee = TransportGuarantee.CONFIDENTIAL, rolesAllowed = {"eshopAdmin"}) )
public class AdminServlet extends HttpServlet {
    @EJB
    private OrderManager orderManager;
    @EJB
    private ProductManager productManager;
    @EJB
    private CustomerFacade customerFacade;

    @EJB
    private CategoryFacade categoryFacade;
    @EJB
    private CategoryManager categoryManager;
    @EJB
    private CustomerOrderFacade customerOrderFacade;


    private Customer customer;
    private CustomerOrder order;

    private List orderList = new ArrayList();
    private List customerList = new ArrayList();
    private Category category;
    private List categoryList = new ArrayList();

    /**
     * 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 {

    }

    // <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 {
        //processRequest(request, response);
        HttpSession session;

        String userPath = request.getServletPath();
        //customer list
        if (userPath.equals("/admin/viewCustomers")){
            customerList = customerFacade.findAll();
            request.setAttribute("customerList", customerList);
        }

        //order list
        else if (userPath.equals("/admin/viewOrders")){
            orderList = customerOrderFacade.findAll();
            request.setAttribute("orderList", orderList);
        }
        //customer records of particular customer
        else if (userPath.equals("/admin/customerRecord")){
            //customer id from user request url
            String customerId = request.getQueryString();
            //get details of customer needs casting back
            customer = customerFacade.find(Integer.parseInt(customerId));
            request.setAttribute("customerRecord", customer);
            //get customer's order details
            order = customerOrderFacade.findByCustomer(customer);
            request.setAttribute("order", order);    
        }

        else if (userPath.equals("/admin/orderRecord")){
            //get customer id from order request
            String orderId = request.getQueryString();
            //get order details by mapping orders and customer
            Map orderMap = orderManager.getOrderDetails(Integer.parseInt(orderId));
            //place order details into app's scope by mapping
            request.setAttribute("customer", orderMap.get("customer"));
            request.setAttribute("products", orderMap.get("products"));
            request.setAttribute("orderRecord", orderMap.get("orderRecord"));
            request.setAttribute("orderedProducts", orderMap.get("orderedProducts"));

        }
        else if (userPath.equals("/admin/showCategory")){
            categoryList = categoryFacade.findAll();
            request.setAttribute("categoryList", categoryList);


        }
        else if (userPath.equals("/admin/addProduct")){
            categoryList = categoryFacade.findAll();
            request.setAttribute("categoryList", categoryList);
        }
        else if (userPath.equals("/admin/logout")){
            try {
                session = request.getSession();
                session.invalidate();

                response.sendRedirect("/e-Shop/admin/");
                return;
            }
            catch (Exception e){
                e.toString();
            }


        }
        //forward request internally
        userPath = "/admin/index.jsp";
        try {
            request.getRequestDispatcher(userPath).forward(request, response);
        }
        catch (ServletException | IOException ex){
            ex.toString();
        }



    }

    /**
     * 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);
        request.setCharacterEncoding("UTF-8");  
        String userPath = request.getServletPath();  
        HttpSession session = request.getSession();


        Validator validator = new Validator() {};
        if (userPath.equals("/admin/addCategory")){

                String name = request.getParameter("name");
                InputStream inputStream = null; // input stream of the upload file
                Part filePart = request.getPart("image");
                if (filePart != null) {
                    // prints out some information for debugging
                    System.out.println(filePart.getName());
                    System.out.println(filePart.getSize());
                    System.out.println(filePart.getContentType());

                    // obtains input stream of the upload file
                    inputStream = filePart.getInputStream();
                }

                boolean validationErrorFlag;
                validationErrorFlag = validator.validateForm(name, request);
                // if validation error found, return  to same
                if (validationErrorFlag == true) {
                    request.setAttribute("validationErrorFlag", validationErrorFlag);

                }
                else {
                    request.setAttribute("name" , name);

                    categoryManager.addCategory(name);

                       // response.sendRedirect("/admin/showCategory");
                    //userPath = "showCategory.jsp";
                       // request.getRequestDispatcher(userPath).forward(request, response);
                        //return;

                    //Category category = categoryManager.addCategory(name);

                }




        }
        else if (userPath.equals("/admin/addProduct")){
            String name = request.getParameter("name");
            String price = request.getParameter("price");
            String description = request.getParameter("description");
            String category_id = request.getParameter("category_id");

                boolean validationErrorFlag;
                validationErrorFlag = validator.validateForm(name, request);
                // if validation error found, return  to same
                if (validationErrorFlag == true) {
                    request.setAttribute("validationErrorFlag", validationErrorFlag);

                }
                else {
                    try{
                    request.setAttribute("name" , name);
                    request.setAttribute("price" , price);
                    request.setAttribute("description" , description);


                        response.sendRedirect("/admin/showCategory");


                    }
                    catch(Exception ex){
                        ex.toString();
                    }
                }    

        }



        // use RequestDispatcher to forward request internally
        String url = userPath + ".jsp";
        try {
            request.getRequestDispatcher(url).forward(request, response);
        }
        catch (ServletException | IOException ex){
            ex.toString();
        }

    }


}

这是管理文件夹

中的index.jsp
<!-- main container starts -->
<div class="container maincontainer">
    <div class="row">
        <div class="col-md-9">
            <h1>Admin Management</h1>
            <p>Here you can manage your site.</p>


            <%-- category list is requested --%>
            <c:if test="${!empty categoryList}">

                    <h2>Category List</h2>
                    <table class="table">
                        <tr>
                            <th>Category Id:</th>
                            <th>Category Name:</th>
                        </tr>
                        <c:forEach var="category" items="${categoryList}" varStatus="iter">
                            <tr>
                            <td>${category.id}</td>
                            <td>${category.name}</td>

                            </tr>
                        </c:forEach>
                    </table>
            </c:if>

            <%-- customerList is requested --%>
            <c:if test="${!empty customerList}">
                    <table class="table">
                        <tr>
                            <th colspan="5">Customers</th>
                        </tr>
                        <tr>
                            <td>Customer Id</td>
                            <td>Name</td>
                            <td>Email</td>
                            <td>Phone</td>
                            <td>Address</td>
                        </tr>
                        <c:forEach var="customer" items="${customerList}" varStatus="iter">
                            <tr onclick="document.location.href='customerRecord?${customer.id}'">
                                <td class="green"><a href="customerRecord?${customer.id}">${customer.id}</a></td>
                                <td class="green"><a href="customerRecord?${customer.id}">${customer.name}</a></td>
                                <td class="green"><a href="customerRecord?${customer.id}">${customer.email}</a></td>
                                <td class="green"><a href="customerRecord?${customer.id}">${customer.phone}</a></td>
                                <td class="green"><a href="customerRecord?${customer.id}">${customer.address}</a></td>
                            </tr>
                        </c:forEach>

                    </table>
            </c:if>
            <%-- orderList is requested --%>
            <c:if test="${!empty orderList}">
                <table class="table">
                    <tr class="header">
                        <th colspan="4">Order List</th>
                    </tr>
                    <tr class="tableHeading">
                        <td>Order Id:</td>
                        <td>Confirmation No:</td>
                        <td>Amount</td>
                        <td>Date created</td>
                    </tr>
                    <c:forEach var="order" items="${orderList}" varStatus="iter">
                        <tr onclick="document.location.href='orderRecord?${order.id}'">
                            <td class="green"><a href="orderRecord?${order.id}" >${order.id}</a></td>
                            <td class="green"><a href="orderRecord?${order.id}" >${order.confirmationNumber}</a></td>
                            <td class="green"><a href="orderRecord?${order.id}" >
                            <fmt:formatNumber type="currency"
                                          currencySymbol="Rs. "
                                          value="${order.amount}"/></a></td>

                            <td class="green"><a href="orderRecord?${order.id}" >
                        <fmt:formatDate value="${order.dateCreated}"
                                        type="both"
                                        dateStyle="short"
                                        timeStyle="short"/></a></td>
                        </tr>
                    </c:forEach>
                </table>
            </c:if>

            <%-- customerRecord is requested --%>
            <c:if test="${!empty customerRecord}">
                <table class="table">
                    <tr class="header">
                        <th colspan="2">Customer Details</th>
                    </tr>
                    <tr>
                        <td style="width: 290px"><strong>Customer id:</strong></td>
                        <td>${customerRecord.id}</td>
                    </tr>
                    <tr>
                        <td><strong>Name:</strong></td>
                        <td>${customerRecord.name}</td>
                    </tr>
                    <tr>
                        <td><strong>Email:</strong></td>
                        <td>${customerRecord.email}</td>
                    </tr>
                    <tr>
                        <td><strong>Phone:</strong></td>
                        <td>${customerRecord.phone}</td>
                    </tr>
                    <tr>
                        <td><strong>Address:</strong></td>
                        <td>${customerRecord.address}</td>
                    </tr>
                    <tr>
                        <td><strong>City / Region:</strong></td>
                        <td>${customerRecord.cityRegion}</td>
                    </tr>
                    <tr><td colspan="2" style="padding: 0 20px"><hr></td></tr>
                    <tr onclick="document.location.href='orderRecord?${order.id}'">
                        <td colspan="2" class="green">
                        <a href="orderRecord?${order.id}">
                        <strong>View Order Summary</strong></a>
                        </td>
                    </tr>
                </table>
            </c:if>

            <%-- orderRecord is requested --%>
            <c:if test="${!empty orderRecord}">

                <table class="table">

                    <tr class="header">
                        <th colspan="3">Order Summary</th>
                    </tr>
                    <tr>
                        <td><strong>order id:</strong></td>
                        <td>${orderRecord.id}</td>
                    </tr>
                    <tr>
                        <td><strong>Confirmation No :</strong></td>
                        <td>${orderRecord.confirmationNumber}</td>
                    </tr>
                    <tr>
                        <td><strong>Date Processed:</strong></td>
                        <td>
                            <fmt:formatDate value="${orderRecord.dateCreated}"
                                            type="both"
                                            dateStyle="short"
                                            timeStyle="short"/></td>
                    </tr>

                    <tr>
                        <td colspan="2">
                            <table class="table tablein">
                               <tr class="">
                                    <td class="rigidWidth">Product</td>
                                    <td class="rigidWidth">Quantity</td>
                                    <td>Price</td>
                                </tr>

                                <tr><td colspan="3" ><hr></td></tr>

                                <c:forEach var="orderedProduct" items="${orderedProducts}" varStatus="iter">

                                    <tr>
                                        <td>
                                            ${products[iter.index].name} 
                                        </td>
                                        <td>
                                              ${orderedProduct.quantity}
                                        </td>
                                        <td class="confirmationPriceColumn">
                                            <fmt:formatNumber type="currency" currencySymbol="Rs. "
                                                              value="${products[iter.index].price * orderedProduct.quantity}"/>
                                        </td>
                                    </tr>

                                </c:forEach>

                                <tr><td colspan="3" style="padding: 0 20px"><hr></td></tr>

                                <tr>
                                    <td colspan="2" id="deliverySurchargeCellLeft"><strong>Delivery Charge:</strong></td>
                                    <td id="deliverySurchargeCellRight">
                                        <fmt:formatNumber type="currency"
                                                          currencySymbol="Rs. "
                                                          value="${initParam.deliverySurcharge}"/></td>
                                </tr>

                                <tr>
                                    <td colspan="2" id="totalCellLeft"><strong>Total Amount:</strong></td>
                                    <td id="totalCellRight">
                                        <fmt:formatNumber type="currency"
                                                          currencySymbol="Rs. "
                                                          value="${orderRecord.amount}"/></td>
                                </tr>
                            </table>
                        </td>
                    </tr>

                    <tr><td colspan="3" style="padding: 0 20px"><hr></td></tr>

                    <tr 
                        onclick="document.location.href='customerRecord?${customer.id}'">
                        <td colspan="2" class="green">

                            <a href="customerRecord?${customer.id}" >
                                <strong>View Customer Details </strong></a>
                        </td>
                    </tr>
                </table>

            </c:if>




        </div>

    <div class="col-md-3">
            <h1>Admin Menu</h1>
            <p class ="admin"><a href="<c:url value='showCategory'/>">View Category</a></p>
            <p class ="admin"><a href="<c:url value='addCategory.jsp'/>">Add Category</a></p>
            <p class ="admin"><a href="<c:url value='upload.jsp'/>">Upload Category Image</a></p>
            <p class ="admin"><a href="<c:url value='addProduct.jsp'/>">Add Product</a></p>
            <p class ="admin"><a href="<c:url value='viewCustomers'/>">View All Customers</a></p>                        
            <p class ="admin"><a href="<c:url value='viewOrders'/>">View All Orders</a></p>
            <p class ="admin"><a href="<c:url value='logout'/>">Log Out</a></p>       
    </div>
    </div>

</div>
<!-- main container ends here -->
<div class="pullfooter"></div>

<div class ="jumbotron">
<p>Jumbo</p>

</div>
<div class="pullfooter"></div>

这是我的 addProduct.jsp 页面,我需要在其中显示我有 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 部分 header.jspf .

<script src="../js/jquery.validate.js" type="text/javascript"></script>

<script type ="text/javascript">
    $(document).ready(function(){
        $("#addCatForm").validate({
            rules: {
                name: {
                    required: true
                }
            }
        });
    });
</script>
<!-- main container starts -->
<div class="container maincontainer">
    <div class="row">
        <div class="col-md-9">
            <h1>Add Product item: </h1>

                <form id ="addForm" action="<c:url value=''/>" method="post">
                    <c:if test="${!empty validationErrorFlag}">
                        <c:if test="${!empty nameError}"><p>Name</p></c:if>
                    </c:if>


                    <p><strong>Product Name:</strong></p>
                    <input class ="form-control" type="text" name="name">
                    <p><strong>Product Category:</strong></p>
                    <select id="selectedCategory" name="category" class="form-control">
                    <option value=""></option>

            <c:forEach var="category" items="${categoryList}" varStatus="iter">

                <option value="${category.getId()}">${category.getName()}</option>

            </c:forEach>

        </select>

                    <p><strong>Product Price:</strong></p>
                    <input class ="form-control" type="text" name="price">
                    <p><strong>Product details:</strong></p>
                    <textarea class ="form-control" type="textarea" name="description" rows="4">

                    </textarea>
                    <br>
                    <p><input class ="btn-success" type="submit" value="Submit"></p>

                </form>

        </div>
        <div class="col-md-3">
        <h1>Admin Menu</h1>
                    <p class ="admin"><a href="<c:url value='showCategory'/>">View Category</a></p>
                    <p class ="admin"><a href="<c:url value='addCategory.jsp'/>">Add Category</a></p>
                    <p class ="admin"><a href="<c:url value='upload.jsp'/>">Upload Category Image</a></p>
                    <p class ="admin"><a href="<c:url value='addProduct.jsp'/>">Add Product</a></p>
                    <p class ="admin"><a href="<c:url value='viewCustomers'/>">View All Customers</a></p>                        
                    <p class ="admin"><a href="<c:url value='viewOrders'/>">View All Orders</a></p>
                    <p class ="admin"><a href="<c:url value='logout'/>">Log Out</a></p>            
        </div>
    </div>

</div>
<!-- main container ends here -->
<div class="pullfooter"></div>

<div class ="jumbotron">
<p>Jumbo</p>
</div>
<div class="pullfooter"></div>

问题出在你的 Servlet 的这一行

else if (userPath.equals("/admin/addProduct")){

替换为

else if (userPath.indexOf("/admin/addProduct")>=0){

我做了这个工作.. 不完全知道 why/how 它工作但解决方案在这里......以防有人需要.. 有一天..

<c:forEach var="category" items="${categories}" varStatus="iter">
<option value="${category.id}">${category.name}</option>
</c:forEach>

试一试..成功了