Sie sind auf Seite 1von 44

DVD Shopping Cart Project

DVD shopping cart project (Java and Oracle) using Struts2


Framework:
Before starting this tutorial, we assume you have already installed Java,
Oracle and NetBeans IDE (version 5.5) and Struts2 (plug ins). We will build
our java application using NetBeans IDE.

Step 1:
At the Net Bean Startup
Select File->New Project

Then Choose Java Web> Web Application then press Next


In the new dialog box, name your project and choose a location for it and
Press Next.

In the next dialog box select the server Glassfish V3 then press Next

In the next dialog box select the Struts2 Framework then press Finish

You will see a default page HelloWorld.jsp and the directory structure like this:

Step2:
In the Directory Structure click on Source Package and then Right click on the
example and select New, click on the Java Class from the drop down menu.

Name your class name and choose the location to be source package and
click Finish.

Edit the Source Code in the ShowAction.java


//ShowAction.java

import java.sql.SQLException;
import javax.servlet.http.*;
import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
public class ShowAction extends ActionSupport implements
ServletRequestAware,ServletResponseAware
{
private HttpServletRequest request;
private HttpServletResponse response;
public void setServletRequest( HttpServletRequest request)
{
this.request=request;
}
public void setServletResponse( HttpServletResponse response)
{
this.response=response;
}
public String execute() throws SQLException
{
ProductDataBean pdb=new ProductDataBean();
ArrayList al=pdb.getProductList();
request.setAttribute("productlist",al);
return SUCCESS;
}
}

Like
the
above
ShowAction.java
add
the
ShoppingCart.java,
RemoveItemAction.java,
ProductDataBean.java,
DVD.java,
CheckoutAction.java, AddToShoppingCartAction.java to the Source Package.

//ShoppingCart.java
import java.util.*;
import java.sql.*;

public class ShoppingCart implements java.io.Serializable {


private Connection connection;
private PreparedStatement addRecord, getRecords;
private Statement statement;
private double totalPrice;
static int CARTID = 1;
protected Vector items;

public ShoppingCart() {
items = new Vector();
}

public Vector getItems() {


return (Vector) items.clone();
}

public void addItem(DVD newItem) {


boolean flag = false;

if (items.size() == 0) {
items.addElement(newItem);
return;
}
for (int i = 0; i< items.size(); i++) {
DVD dvd = (DVD) items.elementAt(i);
if (dvd.getMovie().equals(newItem.getMovie())) {
dvd.setQuantity(dvd.getQuantity()+newItem.getQuantity());
items.setElementAt(dvd,i);
flag = true;
break;
}
}
if (newItem.getQuantity()>0 && (flag == false)) {
items.addElement(newItem);
}
}

public void removeItem(int itemIndex) {


items.removeElementAt(itemIndex);
}

public void completeOrder()


throws Exception {
Enumeration e = items.elements();

connection = ProductDataBean.getConnection();
statement = connection.createStatement();

while (e.hasMoreElements()) {
DVD item = (DVD) e.nextElement();
String itemQuantity = "" + item.getQuantity();
totalPrice = totalPrice + item.getPrice() *
Integer.parseInt(itemQuantity);

String updateString = "INSERT INTO ShoppingCarts " +


" VALUES (" + CARTID + ", '" +
item.getMovie() + "', '" +
item.getRating() + "', '" +
item.getYear() + "', " +
item.getPrice() + ", " +
item.getQuantity() + ")";
statement.executeUpdate(updateString);
}
CARTID ++;
}
public double getTotalPrice() {
return this.totalPrice;
}

public void refreshoriginaldata()


throws Exception {

Enumeration e = items.elements();
connection = ProductDataBean.getConnection();
statement = connection.createStatement();

while (e.hasMoreElements()) {
DVD item = (DVD) e.nextElement();
String movieName = item.getMovie();
int qt =item.getQuantity();
ResultSet srs = statement.executeQuery("select quantity from products
"+
"where movie = '"+movieName+"'");
srs.next();
srs.updateInt("quantity", qt);
srs.updateRow();
}
}

//RemoveItemAction.java
import javax.servlet.http.*;
import com.opensymphony.xwork2.ActionSupport;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

public class RemoveItemAction extends


ServletRequestAware,ServletResponseAware

ActionSupport

implements

{
private HttpServletRequest request;
private HttpServletResponse response;
public void setServletRequest( HttpServletRequest request)
{
this.request=request;
}
public void setServletResponse( HttpServletResponse response)
{
this.response=response;
}
public String execute()
{
// Get the index of the item to remove
int itemIndex = Integer.parseInt(request.getParameter("item"));
HttpSession session = request.getSession();

// Get the cart


ShoppingCart cart = (ShoppingCart) session.getAttribute(
"ShoppingCart");

cart.removeItem(itemIndex);

// Display the cart and allow user to check out or


// order more items

/**

String url="/jsp/ShowProductCatalog.jsp";

ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(request, response);**/
return SUCCESS;
}
}

//ProductDataBean.java

import java.io.*;
import java.sql.*;
import java.util.*;

public class ProductDataBean implements Serializable {


private static Connection connection;
private PreparedStatement addRecord, getRecords;

public ProductDataBean() {
try {
String userName = "sample";
String password = "sample";
//

String url = "jdbc:mysql://localhost/test";


Class.forName ("oracle.jdbc.driver.OracleDriver").newInstance();

connection
=
DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:XE", userName, password);

System.out.println ("Database connection established");


} catch(Exception e){e.printStackTrace();}
}

public static Connection getConnection() {


return connection;
}

public ArrayList getProductList() throws SQLException {


ArrayList productList = new ArrayList();
Statement statement = connection.createStatement();
ResultSet results = statement.executeQuery(
"SELECT * FROM products");
while (results.next()) {
DVD movie = new DVD();
movie.setMovie(results.getString(1));
movie.setRating(results.getString(2));
movie.setYear(results.getString(3));
movie.setPrice(results.getDouble(4));
productList.add(movie);
}
return productList;
}
}
//DVD.java

import java.io.*;

public class DVD implements Serializable {


String m_movie;
String m_rated;
String m_year;
double m_price;
int quantity;
public DVD() {
m_movie = "";
m_rated = "";
m_year = "";
m_price = 0;
quantity = 0;
}

public DVD(String movieName, String movieRate, String movieYear,


double moviePrice, int movieQuantity) {
m_movie = movieName;
m_rated = movieRate;
m_year = movieYear;
m_price = moviePrice;
quantity = movieQuantity;
}
public void setMovie(String title) {
m_movie = title;

}
public String getMovie() {
return m_movie;
}
public void setRating(String rating) {
m_rated = rating;
}
public String getRating() {
return m_rated;
}
public void setYear(String year) {
m_year = year;
}
public String getYear() {
return m_year;
}
public void setPrice(double p) {
m_price = p;
}
public double getPrice() {
return m_price;
}
public void setQuantity(int q) {
quantity = q;
}
public int getQuantity() {

return quantity;
}
}
//CheckoutAction.java
import javax.servlet.http.*;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
public
class
CheckoutAction
extends
ServletRequestAware,ServletResponseAware

ActionSupport

implements

{
private HttpServletRequest request;
private HttpServletResponse response;

public void setServletRequest( HttpServletRequest request)


{
this.request=request;
}
public void setServletResponse( HttpServletResponse response)
{
this.response=response;
}
public String execute()
{
// Get the cart
HttpSession session = request.getSession();

// Get the cart


ShoppingCart cart = (ShoppingCart) session.getAttribute(
"ShoppingCart");
try{
cart.completeOrder();
//

cart.refreshoriginaldata();

} catch(Exception e){
e.printStackTrace();}
// response.sendRedirect(response.encodeRedirectURL(
//

"ShowConfirmation.jsp"));

return SUCCESS;
}
}
//AddToShoppingCartAction.java
import javax.servlet.http.*;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
public class AddToShoppingCartAction extends ActionSupport implements
ServletRequestAware,ServletResponseAware
{
private HttpServletRequest request;
private HttpServletResponse response;

public void setServletRequest( HttpServletRequest request)


{
this.request=request;

}
public void setServletResponse( HttpServletResponse response)
{
this.response=response;
}
public String execute()
{

// Get the DVD from the request


String movieName = request.getParameter("movieName");
String movieRate = request.getParameter("movieRate");
String movieYear = request.getParameter("movieYear");
String price = request.getParameter("moviePrice");

int movieQuantity = Integer.parseInt(


request.getParameter("movieQuantity"));
double moviePrice = Double.parseDouble(price);

// Create this DVD and add to the cart


DVD DVDItem = new DVD(movieName, movieRate, movieYear,
moviePrice, movieQuantity);
HttpSession session = request.getSession();

// Get the cart


ShoppingCart cart = (ShoppingCart) session.
getAttribute("ShoppingCart");

cart.addItem(DVDItem);
/** String url="ShowProductCatalog.jsp";
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(request, response);**/
session.setAttribute("Shoppingcart",cart);
return SUCCESS;
}

}
Now In the Directory Structure click on Web Pages and then Right click on the
example and select New, click on the JSP from the drop down menu.

Name your JSP File and choose the location to be Web Pages and the folder to
be example and click Finish.

Now add the displayshoppingcart.jsp in the respective jsp page

//displayshoppingcart.jsp
<%-- DisplayShoppingCart.jsp --%>
<%@ page contentType="text/html;charset=UTF-8"language="java"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%@ page import="example.*,java.util.*,java.text.*" %>

<% ShoppingCart cart = (ShoppingCart)

session.getAttribute("ShoppingCart");

if (cart == null){
cart = new ShoppingCart();
session.setAttribute("ShoppingCart", cart);
}

Vector items = cart.getItems();

if (items.size() != 0) {
%>
<%-- Display the heading of the shoppingCart --%>

<h1>Shopping Cart</h1>
<br>
<table border=4>
<tr><th>DVD Names<th>Rate<th>Year<th>Price<th>Quantity
<th>Remove
<%

int numItems = items.size();


NumberFormat currency = NumberFormat.getCurrencyInstance();

for (int i=0; i < numItems; i++ ) {


DVD item = (DVD) items.elementAt(i);
%>
<tr>
<s:form action="removeItem"

method="POST">
<td><%= item.getMovie() %></td>
<td><%= item.getRating() %></td>
<td><%= item.getYear() %></td>
<td><%= item.getPrice() %></td>
<td><%= item.getQuantity() %></td>
<td>
<input type="hidden" name= "item" value='<%= i %>'/>
<input type="submit" value="Remove"/> </td>
</s:form>
</tr>
<%

%>
</table>

<s:form action="checkout"
method="POST">
<input type="submit" name="Submit" value="Check out">
</s:form>
<% }
%>

Like
the
above
jsp
page
add
the
showconfirmation.jsp,
showproductcatalog.jsp, and welcome.jsp. the code is listed below
<%-- ShowConfirmation.jsp --%>

<%@ page contentType="text/html;charset=UTF-8"language="java"%>


<%@ taglib uri="/struts-tags" prefix="s" %>
<%@ page import="example.*, java.text.*" %>
<html>
<body>
<h3>Your Order is confirmed!</h3>
<%
DecimalFormat twoDigits = new DecimalFormat("0.00");
String totalPrice =
twoDigits.format(((ShoppingCart)session.getAttribute
("ShoppingCart")).getTotalPrice());
%>

<h3>The total ammount is $<%=totalPrice %></h3>


<% session.invalidate(); %>
</body>
</html>

<%-- ShowProductCatalog.jsp

--%>

<%@ page contentType="text/html;charset=UTF-8"language="java"%>


<%@ taglib uri="/struts-tags" prefix="s" %>
<%@ page import="example.*,java.net.*,java.text.*,java.util.*" %>
<jsp:useBean id = "data" scope= "request"
class = "example.ProductDataBean" />
<html>
<body>

<%-- Call getProductList() of the ProductDataBean to get the DVD product


catalog and put it on the productList
--%>

<% List productList = data.getProductList();


Iterator prodListIterator = productList.iterator();
%>
<p><center>
<h1>DVD Catalog</h1>
<table border:blue bgcolor="rgb(215,225,216)">
<thread>
<tr>
<th>DVD Names</th>
<th>Rating</th>
<th>Year</th>
<th>Price</th>
<th>Quantity</th>
<th>AddCart</th>
</tr>
</thread>
<tbody>

<%-- Display all DVD products row by row on the table, add an addCart
button at the end of each row to allow clients to select
--%>

<% while (prodListIterator.hasNext()){


DVD movie = (DVD)prodListIterator.next();
String movieQuantity = "movieQuantity";
%>
<tr bgcolor="red">
<s:form name="addtoshoppingcart"
action="addtoshoppingcart"
method="POST">
<td ><%= movie.getMovie() %></td>
<td ><%= movie.getRating() %></td>
<td ><%= movie.getYear() %></td>
<td ><%= movie.getPrice() %></td>
<td ><input type = text name = "movieQuantity"
size ="3" /></td>
<td><input align="right" type="submit" value="AddToCart">
<input type="hidden" name= "movieName"
value='<%= movie.getMovie() %>'>
<input type="hidden" name= "movieRate"
value='<%= movie.getRating() %>'>
<input type="hidden" name= "movieYear"
value='<%= movie.getYear() %>'>
<input type="hidden" name= "moviePrice"
value='<%= movie.getPrice() %>'></td>
</s:form>
</tr>
<% }

%>
</tbody>
</table>
<p><hr>
<%-- Display the current shopping Cart by including
DisplayShoppingCart.jsp
--%>
<jsp:include page="displayshoppingcart.jsp" flush="true" />
</center>
</body>
</html>

//Welcome.jsp
<%@ page contentType="text/html;charset=UTF-8"language="java"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<title>WELCOME TO DVD SHOPPING</title>
</head>
<body>
<h>Please click the button to show the Items...</h>
<s:form action = "show">

<s:submit name='CLICK' value='CLICK' accesskey="K" key = "SHOW"/>

</s:form>
</body>
</html>

Step 2: Setting up the oracle driver


Go to the Services section which is beside the projects and click on that :

Inside the Databases Right Click on the Drivers and Select ->New Drivers

A Dialog box will open and in that add the executable .jar file from your PC
which are located in Oracle>Product>11.1.0(version)>db_1>jdbc>lib

After adding the .jar file click OK.

Now in the Drivers you will see the New Driver which is Oracle Thin. Right
Click on the Oracle Thin and press Connect Using ..

Now fill up the Host to be localhost, Port to be 1521 and select service Id
and give your username and password in the respective columns and
check the show JDBC URL.

Now in the same dialog box click on the Advanced Tab which is beside Basic
Setting and select the Schema which you created from the drop down menu
and press ok.

Then expand the jdbc:Oracle Thin to create a table.

Create a table:
Right Click on the Table to create a table

Create a Products Table as shown below wit the respective values

Insert the Record into the Table

To View the inserted data Right Click on the Products Table and Click view
data

Now Create another Table which ShoppingCart in the same way as the above
table. The field values are shown in the below figure

Output:
Now Run the above project and you will get the output to be

After you click on the button the below page will display

Now select the Movie you like and enter the quantity in the respective field
and click on AddToCart and the cart will update like this.

Click on the Checkout button and the Confirmation page will come

Das könnte Ihnen auch gefallen