File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Storing of  Data Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Storing of  Data" Watch "Storing of  Data" New topic
Author

Storing of Data

Alexis Heng
Greenhorn

Joined: Sep 05, 2005
Posts: 6
Hi ranchers,

I am in urgent need for help. I am trying to create a shopping cart whereby instead of hard-coding the item, i load them in from the data base. But i have a problem storing them.

And also in my Shopping Cart, when i compile it, it always say non-static reference variable. How shd i go abt rectifying these problems?

Below is my codes.

public class Catalog
extends HttpServlet {
private Connection con;
String strItemName;
String strItemBrand;
String strCarModel;
String strSpecifications;
String strSerialNumber;
int intQuantity;
double Price;
int count = 0;

public void init() throws ServletException {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch (ClassNotFoundException e) {
System.err.println("init: class not found" + e);
}

try {
con = DriverManager.getConnection("jdbc dbc:jspgODBC");
}
catch (SQLException e) {
System.err.println("init: ODBC fails" + e);
}
}

public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
PrintWriter send = res.getWriter();
res.setContentType("text/html");

try {
Statement stm = con.createStatement();
String sqlStr = "SELECT * FROM ItemDetails";
System.out.println(sqlStr);
ResultSet rs = stm.executeQuery(sqlStr);
ResultSetMetaData info = rs.getMetaData();

int count = 0;
while (rs.next()) {
strItemName = rs.getString("itemName");
strItemBrand = rs.getString("itemBrand");
strCarModel = rs.getString("carModel");
strSpecifications = rs.getString("specifications");
strSerialNumber = rs.getString("serialNumber");
intQuantity = rs.getInt("quantity");
Price = rs.getDouble("sellingPrice");
count++;
}

rs.close();
stm.close();

}

catch (SQLException e) {
send.println("<html><body>");
send.println("Error" + e);
send.println("</body></html>");
}
}

public void destroy() {
try {
con.close();
}

catch (SQLException e) {
System.err.println("destroy:" + e);
}

}

//The following part of codes below is where i am stuck with how to store the iteam.
private CatalogItem[] items = {
new CatalogItem(strSerialNumber, strItemName, strSpecifications,
Price)
};

public CatalogItem getItem(String itemID) {
CatalogItem item;
if (itemID == null) {
return (null);
}
for (int i = 0; i < items.length; i++) {
item = items[i];
if (itemID.equals(item.getItemID())) {
return (item);
}
}
return (null);
}


}



import java.util.*;

public class ShoppingCart {
private ArrayList itemsOrdered;
public ShoppingCart() {
itemsOrdered = new ArrayList();
}

public List getItemsOrdered() {
return (itemsOrdered);
}

public synchronized void addItem(String itemID) {
ItemOrder order;
for (int i = 0; i < itemsOrdered.size(); i++) {
order = (ItemOrder) itemsOrdered.get(i);
if (order.getItemID().equals(itemID)) {
order.incrementNumItems();
return;
}
}
// This is the part where it hit the reference to non-static variable problem.
ItemOrder newOrder = new ItemOrder(Catalog.getItem(itemID));
itemsOrdered.add(newOrder);
}

public synchronized void setNumOrdered(String itemID, int numOrdered) {
ItemOrder order;
for (int i = 0; i < itemsOrdered.size(); i++) {
order = (ItemOrder) itemsOrdered.get(i);
if (order.getItemID().equals(itemID)) {
if (numOrdered <= 0) {
itemsOrdered.remove(i);
}
else {
order.setNumItems(numOrdered);
}
return;
}
}
ItemOrder newOrder = new ItemOrder(Catalog.getItem(itemID));
itemsOrdered.add(newOrder);
}
}

Pls help!! Thanks in advance!
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14146
    
  18

// This is the part where it hit the reference to non-static variable problem.
ItemOrder newOrder = new ItemOrder(Catalog.getItem(itemID));


You get that error because getItem() is not a static method in class Catalog, but you are trying to call it as if it's a static method.

By the way: it is a bad idea to have instance variables in a servlet. The servlet container handles the life cycle of servlets. There is no guarantee that the container creates only one instance of a servlet, and if multiple users are using one instance of a servlet, they will see the same instance variables. You should store state in the HttpSession object, for example, not in servlet instance variables.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Alexis Heng
Greenhorn

Joined: Sep 05, 2005
Posts: 6
Hi Jesper,

Thanks for you advice. I kinda got what u are trying to say.. but i am still not to sure how shd i go abt immplementing it. Rather new to Java Servlets. But i attach the codes below of my session.
Pls help. Thanks u very much.



import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
import java.text.*;

public class orderPage
extends HttpServlet {
private Connection con;
public void init() throws ServletException {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch (ClassNotFoundException e) {
System.err.println("init: class not found" + e);
}

try {
con = DriverManager.getConnection("jdbc dbc:jspgODBC");
}
catch (SQLException e) {
System.err.println("init: ODBC fails" + e);
}
}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
HttpSession session = request.getSession();
ShoppingCart cart;
synchronized (session) {
cart = (ShoppingCart) session.getAttribute("shoppingCart");
if (cart == null) {
cart = new ShoppingCart();
session.setAttribute("shoppingCart", cart);
}
String itemID = request.getParameter("itemID");
if (itemID != null) {
String numItemsString = request.getParameter("numItems");
if (numItemsString == null) {

cart.addItem(itemID);
}
else {
int numItems;
try {
numItems = Integer.parseInt(numItemsString);
}
catch (NumberFormatException nfe) {
numItems = 1;
}
cart.setNumOrdered(itemID, numItems);
}
}
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Status of Your Order";
out.println("<html><head><title>" + title + "</title></head>");
out.println("<body><h1 align = 'center'>" + title + "</h1>");

synchronized (session) {
List itemsOrdered = cart.getItemsOrdered();
double subTotal=0;
double totalCost=0;
if (itemsOrdered.size() == 0) {
out.println("<h2><i>No items in your cart...</i><h2>");
}
else {
out.println("<table border=1 align='center'><tr bgcolor='#C0CAD6'><th>Item Serial Number<th>Product<th>Unit Cost<th>Quanity<th>Total Cost");
ItemOrder order;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
for (int i = 0; i < itemsOrdered.size(); i++) {
order = (ItemOrder)itemsOrdered.get(i);
out.println("<tr>");
out.println("<td>" + order.getItemID() + "</td>");
out.println("<td>" + order.getShortDescription() + "</td>");
out.println("<td>" + formatter.format(order.getUnitCost()) + "</td>");
out.println("<td><form><input type='hidden' name='itemID' value='" +
order.getItemID() + "'>");
out.println("<input type='text' name='numItems' size=3 value='" +
order.getNumItems() + "'><br>");
out.println("<input type='submit' value='Update Order'></form>");
out.println("<td>" + formatter.format(order.getTotalCost()));

totalCost=order.getTotalCost();
subTotal+=totalCost;
System.out.println(subTotal);

}
out.println("<tr><td colspan=5 align='right'><b>SubTotal: </b>" + formatter.format(subTotal) + "</td></tr>");
}

}

}
}
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14146
    
  18

That looks good, you're now using a HttpSession object to store the state of the user's shopping cart.

A HttpSession object stores the state for a single user. If multiple users are using your servlet at the same time, they will have separate HttpSession objects so that their shopping carts don't interfere with each other.

I don't think it is necessary to synchronize on the session object (you can leave out the synchronized(session) { ... }).

Does it work now or do you still have questions? Please feel free to ask...
Alexis Heng
Greenhorn

Joined: Sep 05, 2005
Posts: 6
Hi Jesper,

thanks so much for your advice. My most crucial qns now is I want to store my items by loading them in from the data-base, rather that hard-cording them one by one in the servlet(Catalog.java).

But i do not know how...
I decided to post all the codes that i will be using for my shopping cart below. So u can have a better idea of what i am doing.

But now, the major problems lies in Catalog.java & ShoppingCart.java.
Really need to solve this urgently. Pls help me!!! Thanks in advance.

/**** Codes ****/

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
import java.text.*;

public class orderPage
extends HttpServlet {
private Connection con;
public void init() throws ServletException {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch (ClassNotFoundException e) {
System.err.println("init: class not found" + e);
}

try {
con = DriverManager.getConnection("jdbc dbc:jspgODBC");
}
catch (SQLException e) {
System.err.println("init: ODBC fails" + e);
}
}
//check if users is adding item from the first time
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
HttpSession session = request.getSession();
ShoppingCart cart;
synchronized (session) {
cart = (ShoppingCart) session.getAttribute("shoppingCart");
if (cart == null) {
cart = new ShoppingCart();
session.setAttribute("shoppingCart", cart);
}
String itemID = request.getParameter("itemID");
if (itemID != null) {
String numItemsString = request.getParameter("numItems");
if (numItemsString == null) {

cart.addItem(itemID);
}
else {
int numItems;
try {
numItems = Integer.parseInt(numItemsString);
}
catch (NumberFormatException nfe) {
numItems = 1;
}
cart.setNumOrdered(itemID, numItems);
}
}
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Status of Your Order";
out.println("<html><head><title>" + title + "</title></head>");
out.println("<body><h1 align = 'center'>" + title + "</h1>");

synchronized (session) {
List itemsOrdered = cart.getItemsOrdered();
double subTotal=0;
double totalCost=0;
if (itemsOrdered.size() == 0) {
out.println("<h2><i>No items in your cart...</i><h2>");
}
else {
out.println("<table border=1 align='center'><tr bgcolor='#C0CAD6'><th>Item Serial Number<th>Product<th>Unit Cost<th>Quanity<th>Total Cost");
ItemOrder order;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
for (int i = 0; i < itemsOrdered.size(); i++) {
order = (ItemOrder)itemsOrdered.get(i);
out.println("<tr>");
out.println("<td>" + order.getItemID() + "</td>");
out.println("<td>" + order.getShortDescription() + "</td>");
out.println("<td>" + formatter.format(order.getUnitCost()) + "</td>");
out.println("<td><form><input type='hidden' name='itemID' value='" +
order.getItemID() + "'>");
out.println("<input type='text' name='numItems' size=3 value='" +
order.getNumItems() + "'><br>");
out.println("<input type='submit' value='Update Order'></form>");
out.println("<td>" + formatter.format(order.getTotalCost()));

totalCost=order.getTotalCost();
subTotal+=totalCost;
System.out.println(subTotal);

}
out.println("<tr><td colspan=5 align='right'><b>SubTotal: </b>" + formatter.format(subTotal) + "</td></tr>");
}

}

}
}



import java.util.*;

//a shopping cart to track orders
public class ShoppingCart {
private ArrayList itemsOrdered;
public ShoppingCart() {
itemsOrdered = new ArrayList();
}

public List getItemsOrdered() {
return (itemsOrdered);
}

public synchronized void addItem(String itemID) {
ItemOrder order;
for (int i = 0; i < itemsOrdered.size(); i++) {
order = (ItemOrder) itemsOrdered.get(i);
if (order.getItemID().equals(itemID)) {
order.incrementNumItems();
return;
}
}
//If i load from a database, how shd i edit this line of code below so that i can reference a non-static variable???

ItemOrder newOrder = new ItemOrder(Catalog.getItem(itemID));
itemsOrdered.add(newOrder);
}

public synchronized void setNumOrdered(String itemID, int numOrdered) {
ItemOrder order;
for (int i = 0; i < itemsOrdered.size(); i++) {
order = (ItemOrder) itemsOrdered.get(i);
if (order.getItemID().equals(itemID)) {
if (numOrdered <= 0) {
itemsOrdered.remove(i);
}
else {
order.setNumItems(numOrdered);
}
return;
}
}
ItemOrder newOrder = new ItemOrder(Catalog.getItem(itemID));
itemsOrdered.add(newOrder);
}
}

//save the item's information
public class ItemOrder {
private CatalogItem item;
private int numItems;


public ItemOrder(CatalogItem item) {
setItem(item);
setNumItems(1);
}

public CatalogItem getItem() {
return (item);
}

protected void setItem(CatalogItem item) {
this.item = item;
}

public String getItemID() {
return (getItem().getItemID());
}

public String getShortDescription() {
return (getItem().getShortDescription());
}

public String getLongDescription() {
return (getItem().getLongDescription());
}

public double getUnitCost() {
return (getItem().getCost());
}

public int getNumItems() {
return (numItems);
}

public void setNumItems(int n) {
this.numItems = n;
}

public void incrementNumItems() {
setNumItems(getNumItems() + 1);
}

public void cancelOrder() {
setNumItems(0);
}

public double getTotalCost() {
return (getNumItems() * getUnitCost());
}

}

//Describe the catalog item for the online store
public class CatalogItem {
private String itemID;
private String shortDescription;
private String longDescription;
private double cost;

public CatalogItem(String itemID, String shortDescription,
String longDescription, double cost) {
setItemID(itemID);
setShortDescription(shortDescription);
setLongDescription(longDescription);
setCost(cost);
}

public String getItemID() {
return (itemID);
}

protected void setItemID(String itemID) {
this.itemID = itemID;
}

public String getShortDescription() {
return (shortDescription);
}

protected void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}

public String getLongDescription() {
return (longDescription);
}

protected void setLongDescription(String longDescription) {
this.longDescription = longDescription;
}

public double getCost() {
return (cost);
}

protected void setCost(double cost) {
this.cost = cost;
}
}


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

//A catalog that list the items available in inventory
public class Catalog
extends HttpServlet {
private Connection con;
String strItemName;
String strItemBrand;
String strCarModel;
String strSpecifications;
String strSerialNumber;
int intQuantity;
double Price;
int count = 0;

public void init() throws ServletException {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch (ClassNotFoundException e) {
System.err.println("init: class not found" + e);
}

try {
con = DriverManager.getConnection("jdbc dbc:jspgODBC");
}
catch (SQLException e) {
System.err.println("init: ODBC fails" + e);
}
}

public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
PrintWriter send = res.getWriter();
res.setContentType("text/html");

try {
Statement stm = con.createStatement();
String sqlStr = "SELECT * FROM ItemDetails";
System.out.println(sqlStr);
ResultSet rs = stm.executeQuery(sqlStr);
ResultSetMetaData info = rs.getMetaData();
/* String strItemName;
String strItemBrand;
String strCarModel;
String strSpecifications;
String strSerialNumber;
int intQuantity;
double Price;*/
int count = 0;
while (rs.next()) {
strItemName = rs.getString("itemName");
strItemBrand = rs.getString("itemBrand");
strCarModel = rs.getString("carModel");
strSpecifications = rs.getString("specifications");
strSerialNumber = rs.getString("serialNumber");
intQuantity = rs.getInt("quantity");
Price = rs.getDouble("sellingPrice");
count++;
}

rs.close();
stm.close();

}

catch (SQLException e) {
send.println("<html><body>");
send.println("Error" + e);
send.println("</body></html>");
}
}

public void destroy() {
try {
con.close();
}

catch (SQLException e) {
System.err.println("destroy:" + e);
}

}


//Current Problem: The inventory is stored by hard-coding, but i want to dynamically store the values that are retrived from the database.
For e.g /*private CatalogItem[] items = {
new CatalogItem(strSerialNumber, strItemName, strSpecifications,
Price)
};*/
How do i go abt it??

private static CatalogItem[] items = {
new CatalogItem("89312", "Beetle Floor Liner", "The servelst is..",
39.95),
new CatalogItem("332252", "Corolla Air Filter", "The servelst is..",
39.95),
};

public static CatalogItem getItem(String itemID) {
CatalogItem item;
if (itemID == null) {
return (null);
}
for (int i = 0; i < items.length; i++) {
item = items[i];
if (itemID.equals(item.getItemID())) {
return (item);
}
}
return (null);
}

}

/**** End of codes ********/
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14146
    
  18

For storing data in a database in Java, you use JDBC. Your servlet already contains a few lines of code to open a database connection.

I can't explain everything in a forum topic - have a look at the following tutorial: JDBC(TM) Database Access - it will explain you step by step how to work with databases in Java.
Alexis Heng
Greenhorn

Joined: Sep 05, 2005
Posts: 6
Erm... i think u dun quite get my point.
I know how to insert and retrive data from databases.

My qns is once i retrived this information from the databases,
how shd i store it an array???

For example,

Array(id, name, description)

I know that an array only allows us to store one information per element.
But what i wan now is to store multiple information for EACH element.

How to go abt doing that?
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3536
    
  15
You create a class to hold all the information and then store instances of that class in the array.


Joanne
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Storing of Data