Sunday, April 19, 2009

Write a program to display an online shopping cart Web page with a drop down menu

Write a program to display an online shopping cart Web page with a drop down menu. The Web page should have one button to add an item to the cart, and another button to remove an item from the cart. The Web page should display the changes made to the cart.

Solution:
The file used in this exercise is cart.jsp
<html>
<%
java.util.Vector v = (java.util.Vector)session.getAttribute("array");
if (v == null)
{
v = new java.util.Vector();
}
String i = null;
String submit = request.getParameter("submit");

if (submit == null)
{
submit = "";
}
if (submit.equals("add") || submit.equals(""))
{
v.addElement(request.getParameter("item"));
%>
<br> Your cart Contains :
<ol>
<%
String[] items = new String[v.size()];
v.copyInto(items);
for (int ix=1; ix < items.length; ix++) {
%>
<li> <% out.print(items[ix]);
}
%>
</ol>

<%
}
if (submit.equals("remove"))
{
String removeitem=request.getParameter("item");
if(v.contains(removeitem))
{
v.removeElement(removeitem);
}
else
{
out.println("element not found in vector");
}

%>
<br> Your cart Contains :
<ol>
<%
String[] items = new String[v.size()];
v.copyInto(items);
for (int ix=1; ix<items.length; ix++) {
%>
<li> <% out.print(items[ix]);
}
%>
</ol>

<%
}
session.setAttribute("array",v);
%>
</font>
<hr>
<font size = 3>
<form type=POST>
<BR>
Please Select the item to add or remove:
<br>
Add / Remove Item:
<select name="item">
<option>Floppy
<option>CD
<option>Keyboard
</select>
<br> <br>
<input type=submit name="submit" value="add">
<input type=submit name="submit" value="remove">
</form>
</font>
</html>

Enter the code in Notepad, and save the file as Cart.jsp in %TOMCAT_HOME%/webapps/ session.

The output of the program is as shown in Figure 12.1.

Figure 12.1: Shopping cart page

Figure 12.2 Error page

0 nhận xét: