dvd cart tutorial-1
TRANSCRIPT
-
7/30/2019 DVD Cart Tutorial-1
1/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.
-
7/30/2019 DVD Cart Tutorial-1
2/38
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:
-
7/30/2019 DVD Cart Tutorial-1
3/38
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.
-
7/30/2019 DVD Cart Tutorial-1
4/38
Name your class name and Package name, choose the location to be source package and click
Finish.
-
7/30/2019 DVD Cart Tutorial-1
5/38
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() {
-
7/30/2019 DVD Cart Tutorial-1
6/38
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() {
-
7/30/2019 DVD Cart Tutorial-1
7/38
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
-
7/30/2019 DVD Cart Tutorial-1
8/38
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();
}
-
7/30/2019 DVD Cart Tutorial-1
9/38
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);
}
}
-
7/30/2019 DVD Cart Tutorial-1
10/38
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() + "', " +
-
7/30/2019 DVD Cart Tutorial-1
11/38
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;
-
7/30/2019 DVD Cart Tutorial-1
12/38
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())
-
7/30/2019 DVD Cart Tutorial-1
13/38
{
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.
-
7/30/2019 DVD Cart Tutorial-1
14/38
Create the AddToShoppingCartServlet.
-
7/30/2019 DVD Cart Tutorial-1
15/38
//AddToShoppingCartServlet.java
-
7/30/2019 DVD Cart Tutorial-1
16/38
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);
-
7/30/2019 DVD Cart Tutorial-1
17/38
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.*;
-
7/30/2019 DVD Cart Tutorial-1
18/38
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;
-
7/30/2019 DVD Cart Tutorial-1
19/38
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);
}
-
7/30/2019 DVD Cart Tutorial-1
20/38
}
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
-
7/30/2019 DVD Cart Tutorial-1
21/38
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)
{
%>
Shopping Cart
DVD NamesRateYearPriceQuantityRemove
-
7/30/2019 DVD Cart Tutorial-1
22/38
{
DVD item = (DVD) items.elementAt(i);
%>
-
7/30/2019 DVD Cart Tutorial-1
23/38
//ShowConfirmation.jsp
Your Order is confirmed!
The total amount is $
-
7/30/2019 DVD Cart Tutorial-1
24/38
//ShowProductCatalog.jsp
DVD Catalog
DVD Names
Rate
Year
Price
Quantity
AddCart
-
7/30/2019 DVD Cart Tutorial-1
25/38
-
7/30/2019 DVD Cart Tutorial-1
26/38
%>
//web.xml
AddToShoppingCartServlet
cart.AddToShoppingCartServlet
CheckoutServlet
cart.CheckoutServlet
RemoveItemServlet
-
7/30/2019 DVD Cart Tutorial-1
27/38
cart.RemoveItemServlet
AddToShoppingCartServlet
/AddToShoppingCartServlet
CheckoutServlet
/CheckoutServlet
RemoveItemServlet
/RemoveItemServlet
30
ShowProductCatalog.jsp
Step 2: Setting up the MySQL driver
Go to the Services section which is beside the projects and click on that :
-
7/30/2019 DVD Cart Tutorial-1
28/38
Inside the Databases Right Click on the Drivers and Select ->New Drivers
-
7/30/2019 DVD Cart Tutorial-1
29/38
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.
-
7/30/2019 DVD Cart Tutorial-1
30/38
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.
-
7/30/2019 DVD Cart Tutorial-1
31/38
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.
-
7/30/2019 DVD Cart Tutorial-1
32/38
-
7/30/2019 DVD Cart Tutorial-1
33/38
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.
-
7/30/2019 DVD Cart Tutorial-1
34/38
Create ShoppingCarts table: This process is the same as the one we used to create the
products table, but without any values inserted.
-
7/30/2019 DVD Cart Tutorial-1
35/38
web.xml: We need to set Welcome page. open the web.xml and click the Pages, choose
ShowProductCatalog.jsp as Welcome Files.
-
7/30/2019 DVD Cart Tutorial-1
36/38
Deployment: Right click on the project name and select Clean and Build. Then you will find war
file in the dist folder.
-
7/30/2019 DVD Cart Tutorial-1
37/38
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
-
7/30/2019 DVD Cart Tutorial-1
38/38
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