Sei sulla pagina 1di 38

DVD Shopping Cart Project

DVD shopping cart project (Java and MySQL): Before starting this tutorial, we assume you have already installed Java, MySQL and NetBeans IDE (version 7.0). 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 Apache Tomcat 7.0.11 (Netbeans 6.9 , Tomcat 6.0)then press Finsh

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 it and select New, click on the JavaBeans Component from the drop down menu.

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

Edit the Source Code in the ShowAction.java //DVD.java package cart;

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; } }

Like the above DVD.java add the ShoppingCart.java, ProductDataBean.java to the Source Package.

//ShoppingCart.java

package cart;

import java.util.*; import java.io.*; 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 movieName = item.getMovie();

String updateString = "INSERT INTO shoppingCart " + " VALUES (" + CARTID + ", '" + item.getMovie() + "', '" + item.getRating() + "', '" + item.getYear() + "', " +

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

//ProductDataBean.java (Dont forget to fill your database password in the code)

package cart;

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

public class ProductDataBean implements Serializable { private static Connection connection;

public ProductDataBean() { try { String userName = "root"; String password = ""; String url = "jdbc:mysql://localhost/eshopdb"; Class.forName("com.mysql.jdbc.Driver").newInstance(); connection = DriverManager.getConnection(url,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; }

} Create a new Java Servlet: Right click on the ShoppingCart project and select New-> Servlet. For Java name, enter AddToShoppingCartServlet, for package, enter cart, and then click OK. Add code below. Repeat this procedure for Java servlets called CheckoutServlet and RemoveItemServlet.

Create the AddToShoppingCartServlet.

//AddToShoppingCartServlet.java

package cart;

import javax.servlet.*; import javax.servlet.http.*; import java.io.*;

public class AddToShoppingCartServlet extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

// 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");

if (cart == null) { cart = new ShoppingCart();

session.setAttribute("ShoppingCart", cart); }

cart.addItem(DVDItem); String url="/ShowProductCatalog.jsp"; ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request, response); } } //CheckoutServlet.java package cart;

import javax.servlet.*;

import javax.servlet.http.*; import java.io.*; import java.net.*;

public class CheckoutServlet extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { HttpSession session = request.getSession();

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

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

response.sendRedirect(response.encodeRedirectURL("ShowConfirmation.jsp")); } } //RemoveItemServlet.java package cart;

import javax.servlet.*; import javax.servlet.http.*; import java.io.*;

public class RemoveItemServlet extends HttpServlet {

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

int itemIndex = Integer.parseInt(request.getParameter("item"));

HttpSession session = request.getSession();

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

cart.removeItem(itemIndex);

String url = "/ShowProductCatalog.jsp"; ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(request, response); }

} Create a new JSP file: Right click on the ShoppingCart project you just created and select New->JSP. For JSP name, enter DisplayShoppingCart and click OK. Add code below. Ignore the HTML error. Repeat this procedure for new JSP files called ShowConfirmation and ShowProductCatalog.

//DisplayShoppingCart.jsp <%@ page import="cart.*,java.util.*,java.text.*" %>

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

if (cart == null) { cart = new ShoppingCart(); session.setAttribute("ShoppingCart", cart); System.out.println("test------"); } System.out.println("-------test");

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> <form action="RemoveItemServlet" 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> </form>

</tr>

<% } %> </table>

<form

action="CheckoutServlet" method="POST">

<input type="submit" name="Submit" value="Check out"> </form>

<% } %>

//ShowConfirmation.jsp <%@ page import="cart.*, java.text.*" %> <html> <body> <h1>Your Order is confirmed!</h1> <% DecimalFormat twoDigits = new DecimalFormat("0.00"); String totalPrice = "";

try { totalPrice = session.getAttribute("ShoppingCart")).getTotalPrice()); twoDigits.format(((ShoppingCart)

} catch (Exception e) { System.out.println("null session, already checked out"); } %>

<h1>The total amount is $<%=totalPrice %></h1> <% session.invalidate(); %> </body> </html>

//ShowProductCatalog.jsp <%@ page import = "java.util.*" import="cart.*,java.net.*,java.text.*" %> <jsp:useBean id = "data" scope= "request" class = "cart.ProductDataBean" />

<html> <body>

<% List productList = data.getProductList(); Iterator prodListIterator = productList.iterator(); %>

<p> <center> <h1>DVD Catalog</h1>

<table border="1"> <thread><tr> <th>DVD Names</th> <th>Rate</th> <th>Year</th> <th>Price</th> <th>Quantity</th> <th>AddCart</th> </tr></thread>

<% while (prodListIterator.hasNext()) { DVD movie = (DVD)prodListIterator.next(); String movieQuantity = "movieQuantity"; %> <tr> <form name="AddToShoppingCartServlet" action="AddToShoppingCartServlet" 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="5" /></td> <td> <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() %>'> <input type="submit" value="AddToCart"> </form> </td>

</tr> <% }

%> </table>

<p> <hr> <jsp:include page="DisplayShoppingCart.jsp" flush="true" />

</center>

</body> </html> //web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <servlet> <servlet-name>AddToShoppingCartServlet</servlet-name> <servlet-class>cart.AddToShoppingCartServlet</servlet-class> </servlet> <servlet> <servlet-name>CheckoutServlet</servlet-name> <servlet-class>cart.CheckoutServlet</servlet-class> </servlet> <servlet> <servlet-name>RemoveItemServlet</servlet-name>

<servlet-class>cart.RemoveItemServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AddToShoppingCartServlet</servlet-name> <url-pattern>/AddToShoppingCartServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>CheckoutServlet</servlet-name> <url-pattern>/CheckoutServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>RemoveItemServlet</servlet-name> <url-pattern>/RemoveItemServlet</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file>ShowProductCatalog.jsp</welcome-file> </welcome-file-list> </web-app> Step 2: Setting up the MySQL 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 NetBeans 7.0\ide\modules\ext\mysql-connector-java-5.1.13-bin.jar

After adding the .jar file click OK.

Now in the Drivers you will see the New Driver which is MySQL(Connector/J driver). Right Click on the MySQL(Connector/J driver) and press Connect Using ..

Then you need to register MySQL with NetBeans.

Fill in the password of your database.

Create a database instance in NetBeans: After you have connected to the database, you can begin exploring how to create tables, populate them with data, and modify data maintained in tables. This allows you to take a closer look at the functionality offered by the Database explorer. Create the MySQL Database eshopdb In the NetBeans Services tag right click on the MySQL Server at Localhost and select Connect and then Create Database. For New Database Name, enter test.

Create products table: Right click on the Tables inside jdbc:mysql://localhost/eshopdb and select Create Table. For table name, enter products. if you want to insert more, click Add column. When you are done, click OK.

Insert values of products: Right click the products table you just created and select View Data. Click on the button on the top left-hand side and enter the values.

Create ShoppingCarts table: This process is the same as the one we used to create the products table, but without any values inserted.

web.xml: We need to set Welcome page. open the web.xml and click the Pages, choose ShowProductCatalog.jsp as Welcome Files.

Deployment: Right click on the project name and select Clean and Build. Then you will find war file in the dist folder.

Copy the war file into Tomcat

Then Close the NetBeans and Start the Tomcat, Type the address into the browser.

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

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

Potrebbero piacerti anche