Download Update - KSU Web Home

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
4.5 Lab 2: Shopping Cart Development with NetBeans
Before you begin, make sure you have the following software installed:
NetBeans IDE 6.9 or higher, Java SE Development Kit (JDK™) version 5.0 or
higher , and MySQL database.
(Xampp with the Tomcat plugin has all the above software.)
4.6.1 JDBC Driver for MySQL
1. Install and configure the database: We assume that you have installed and
configured the MySQL database; if not, go to:
http://www.netbeans.org/kb/docs/ide/mysql.html and read the Installing and
Configuring the Database section.
You need to register MySQL with NetBeans.
The MySQL registration installs the MySQL JDBC driver.
2. 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.
1. Create the MySQL Database eshopdb
In the NetBeans Services tag right-click on the MySQL Server at Localhost and
select Create Database. For New Database Name, enter test.
2. Create products table: Right-click on the Tables inside
jdbc:mysql://localhost:3306/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.
3. 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.
4. Create ShoppingCarts table : This process is the same as the onee we used to
create the products table, but without any values inserted.
3. Create a Java web project in NetBeans: We have created the database and now we
need to create the Java web project to access to the database.
1. Create Java web project: From File → New Project, select Java Web →
Web Application. Click OK. For Project Name, enter shoppingCart. For
Server, choose Tomcat. The Wizard will guide you through the rest of the
procedure. Accept all default settings.
2. Create a new Java bean: Right-click on the shoppingCart project and select
New → other → JavaBean Object → JavaBean Component. For Java
name, enter DVD, for package, enter cart, and then click OK. Add code
below. Repeat this procedure for Java servlets called ProductDataBean and
ShoppingCart.
All the related source code is listed here again for your convenience.
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;
}
}
ProductDataBean.java (Don’t 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;
private PreparedStatement addRecord, getRecords;
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;
}
}
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;
}
}
3. 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(
"/shoppingCart/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
{
// remove item
int itemIndex =
Integer.parseInt(request.getParameter("item"));
HttpSession session = request.getSession();
// Get the cart
ShoppingCart cart = (ShoppingCart) session.
getAttribute("ShoppingCart");
/* if (cart == null)
{
cart = new ShoppingCart();
session.setAttribute("ShoppingCart", cart);
}*/
cart.removeItem(itemIndex);
// Show the cart and let user check out or order more
String url="/ShowProductCatalog.jsp";
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(url);
rd.forward(request, response);
}
}
4. 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 andShowProductCatalog.
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);
}
Vector items = cart.getItems();
if (items.size() != 0)
{
%>
<%-- show the shoppingCart heading--%>
<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="/shoppingCart/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="/shoppingCart/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 =
twoDigits.format(((ShoppingCart)session.getAttribute("S
hoppingCart")).getTotalPrice());
%>
<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="addtoShoppingCart"
action="/shoppingCart/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"> </td>
</form>
</tr>
<%
}
%>
</table>
<p>
<hr>
<jsp:include page="DisplayShoppingCart.jsp"
flush="true" />
</center>
</body>
</html>
5. Insert welcome page: Select Pages and for Welcome Files, enter
ShowProductCatalog.jsp. Now we have web.xml set up and XML code is
generated automatically.
3. Run the Project.
Build and Run the program
Enter quantity and Click on AddToCart.
3. Shopping Cart check out.
Related documents