137
137

Reputation: 821

Calling a servlet from a dynamically generated form

I'm making a mock up of an online store for school. I'm storing my products in an SQL Database. I want to display all products in the DB with buttons next to them that will send their ID to the cart_servlet. In order to display the products I'm generating a table like so:

public static String getInventory(){
    String result = "<table>";
    for ( Product p : DAO_Product.getProducts() ) {
        result = result + "<tr>"
                + "<td>" + p.getName() + "</td>"
                + "<td><img src=\"resources/images/" + p.getImage() + "\" alt=\"Duke waving his hand\"></td>"
                + "<td>" + p.getDollars() + "</td>"
                + "<td>" + p.getPennies() + "</td>"
                + "<td>" + p.getStock() + "</td>"
                + "<td>" + p.getDescription() + "</td>"

                //creates a form consisting of one button and a hidden value
                //clicking the button should submit the corresponding hidden value
                + "<td><form action=\"${pageContext.request.contextPath}/cart_servlet\" method=\"post\">"
                + "<input type=\"hidden\" name=\"product\" value=\"" + p.getId() + "\" />"
                + "<input type=\"submit\" name=\"submit\" value=\"Add to Cart\" />"
                + "</form>"
                //End Form

                + "</tr>";
    }
}

This creates the correct table as I envisioned and the HTML it generates looks correct:

output form

<table><tr><td>Caverna</td>
    <td><img src="resources/images/caverna.jpg" alt="sampleImage"></td>
    <td>112</td><td>12</td><td>34</td>
    <td> you are the bearded leader of a small dwarf family which lives in a little cave in the mountains. Together, you</td>

<td><form action ="${pageContext.request.contextPath}/cart_servlet" method="post">
    <input type="hidden" name="product" value="4" />
    <input type="submit" name="submit" value="Add to Cart" />
</form>

However when I click the button I am presented with: 'HTTP Status 404 - Not Found' description: 'The requested resource is not available'

The Servlet I am requesting is my 'CartServlet':

@WebServlet( "/cart_servlet" )
public class CartServlet extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String result;
    Status status = new Status();
    req.setAttribute( "status", status );
    //RequestDispatcher view = req.getRequestDispatcher( "browseProducts.jsp" );
    if ( req.getParameter( "submit" ) != null ) {
    }
    //view.forward( req, resp );
    }
}

I've commenting out everything in my 'CartServlet' and I am sure that it probably cant get the context somehow or find the class but I am unsure about how to fix this.

Upvotes: 1

Views: 820

Answers (1)

137
137

Reputation: 821

It turns out I was approaching this all wrong. Instead I should have built the table within my JSP using JSTL. With the following code I was able to delete 'getInventory()':

The First step is to add the following line to the top of your JSP:

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

Note Ensure you have downloaded the JSTL library and added it to your project. You can find it here.

The Second step is to declare any variables you would need. In this case I require an ArrayList of 'Products':

<%
    ArrayList<Product> products = DAO_Product.getProducts();
    //Set an attribute to reference our Arraylist
    pageContext.setAttribute( "products", products );
 %>

Now we are ready to build our table. The table will display information about each product and have a button in the last column that will call 'cart_servlet'. We are going to use the 'forEach' from 'JSTL':

<table border="1" cellpadding="5" >
    <tr>
        <th>Name</th>
        <th>Image</th>
        <th>Price</th>
        <th>Description</th>
        <th>Stock</th>
        <th>Add to Cart?</th>
    </tr>
    <c:forEach var="p" items="${products}" >
        <tr>
            <td>${p.name}</td>
            <td><img src="resources/images/${p.getImage()}" alt="Cool Pic"></td>
            <td>$${p.dollars}.${p.pennies}</td>
            <td>${p.description}</td>
            <td>${p.stock}</td>
            <td>
                <form action="${pageContext.request.contextPath}/cart_servlet" method="post">
                    <input type="hidden" name="productID" value="${p.id}">
                    <input type="submit" name="addToCart" value="Add to Cart">
                </form>
            </td>
        </tr>
    </c:forEach>
</table>

Upvotes: 1

Related Questions