A Very Simple WebSphere J2EE Model 2 Sample


This document demonstrates how to create a complete (and very simple) J2EE project in WebSphere Studio.

This sample project is in MVC (Model-View-Control) Model 2 architecture. It has all the elements except linking to database. The original code is from web site http://www.javaworld.com/javaworld/jw-12-1999/jw-12-ssj-jspmvc_p.html. I reconstructed it to work in WebSphere Studio.


Files:

View: Three JSP pages are used as view. They are Eshop.jsp, Checkout.jsp, and Cart.jsp
Controller: Servlet program, which is ShoppingServlet.java
Model: JavaBean, which is CD.java

How to create the files:

  1. Start WebSphere Studio.
  2. Create a new project by selecting File | New |Dynamic Web Project, enter project name Model2Sample. This will build the complete project structure.
  3. Highlight WebContent, click right mouse, select New | JSP file to create all three JSP files.
  4. Highlight JavaSource, click right mouse, select Servlet, enter class name ShoppingServlet. Step to next to exam the servlet mapping is added properly. In this sample, the Servlet is ShoppingServlet, mapping is \ShoppingServlet. You can look web.xml file later to verify or modify the servlet mapping (WebContent\WEB-INF\web.xml).
  5. Highlight JavaSource, click right mouse, select Others. Then select Java, Java Class. Enter CD as class name and shopping as package name.

How the files are related (Modification to the original code):

The file structure at WebSphere look as following

Build the project. Highlight file Eship.jsp, click right mouse, select Run on Server to start the server and run the web pages. If you make any change in the xml file, you have to stop and then restart the server.

Source Code:

EShop.jsp

<%@ page session="true" %>
<%@ page import= "shopping.*" %>

<html>
<head>
<title>Music Without Borders</title>
</head>
<body bgcolor="#33CCFF">
<font face="Times New Roman,Times" size="+3">
Music Without Borders
</font>
<hr><p>
<center>
<form name="shoppingForm"
action="/Model2Sample/ShoppingServlet" method="POST">
<b>CD:</b>
<select name=CD>
<option>Yuan | The Guo Brothers | China | $14.95</option>
<option>Drums of Passion | Babatunde Olatunji | Nigeria | $16.95</option>
<option>Kaira | Tounami Diabate| Mali | $16.95</option>
<option>The Lion is Loose | Eliades Ochoa | Cuba | $13.95</option>
<option>Dance the Devil Away | Outback | Australia | $14.95</option>
<option>Record of Changes | Samulnori | Korea | $12.95</option>
<option>Djelika | Tounami Diabate | Mali | $14.95</option>
<option>Rapture | Nusrat Fateh Ali Khan | Pakistan | $12.95</option>
<option>Cesaria Evora | Cesaria Evora | Cape Verde | $16.95</option>
<option>Ibuki | Kodo | Japan | $13.95</option>
</select>
<b>Quantity: </b><input type="text" name="qty" SIZE="3" value=1>
<input type="hidden" name="action" value="ADD">
<input type="submit" name="Submit" value="Add to Cart">
</form>
</center>
<p>
<jsp:include page="Cart.jsp" flush="true" />
</body>
</html>


Cart.jsp

<%@ page session="true" %>
<%@ page import="java.util.*" %>
<%@ page import= "shopping.CD" %>
<%
Vector buylist = (Vector) session.getAttribute("shopping.shoppingcart");
if (buylist != null && (buylist.size() > 0)) {
%>
<center>
<table border="0" cellpadding="0" width="100%" bgcolor="#FFFFFF">
<tr>
<td><b>ALBUM</b></td>
<td><b>ARTIST</b></td>
<td><b>COUNTRY</b></td>
<td><b>PRICE</b></td>
<td><b>QUANTITY</b></td>
<td></td>
</tr>
<%
for (int index=0; index < buylist.size();index++) {
CD anOrder = (CD) buylist.elementAt(index);
%>
<tr>
<td><b><%= anOrder.getAlbum() %></b></td>
<td><b><%= anOrder.getArtist() %></b></td>
<td><b><%= anOrder.getCountry() %></b></td>
<td><b><%= anOrder.getPrice() %></b></td>
<td><b><%= anOrder.getQuantity() %></b></td>
<td>
<form name="deleteForm"
action="/Model2Sample/ShoppingServlet"
method="POST">
<input type="submit" value="Delete">
<input type="hidden" name= "delindex" value='<%= index %>'>
<input type="hidden" name="action" value="DELETE">
</form>
</td>
</tr>
<% } %>
</table>
<p>
<form name="checkoutForm"
action="/Model2Sample/ShoppingServlet"
method="POST">
<input type="hidden" name="action" value="CHECKOUT">
<input type="submit" name="Checkout" value="Checkout">
</form>
</center>
<% } %>

 

 

Checkout.jsp

<%@ page session="true" import="java.util.*, shopping.CD" %>

<html><head><title>Music Without Borders Checkout</title></head>
<body bgcolor="#33CCFF">
<font face="Times New Roman,Times" size=+3> Music Without Borders Checkout</font><hr>
<p><center><table border="0" cellpadding="0" width="100%" bgcolor="#FFFFFF"><tr>
<td><b>ALBUM</b></td>
<td><b>ARTIST</b></td><td><b>COUNTRY</b></td>
<td><b>PRICE</b></td><td><b>QUANTITY</b></td>
<td></td></tr>
<% Vector buylist = (Vector) session.getAttribute("shopping.shoppingcart");
String amount = (String) request.getAttribute("amount");
for (int i=0; i < buylist.size();i++)
{
CD anOrder = (CD) buylist.elementAt(i);%>
<tr><td><b><%= anOrder.getAlbum() %></b></td>
<td><b><%= anOrder.getArtist() %></b></td>
<td><b><%= anOrder.getCountry() %></b></td>
<td><b><%= anOrder.getPrice() %></b></td>
<td><b><%= anOrder.getQuantity() %></b></td>
</tr>
<% } session.invalidate();%>
<tr><td> </td>
<td> </td>
<td><b>TOTAL</b></td>
<td><b>$<%= amount %></b></td>
<td> </td></tr>
</table>
<p><a href="EShop.jsp">Shop some more!</a></center>
</body></html>

ShoppingServlet.java

---------------------------------
/*
 * Created on Nov 13, 2003
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */

/**
 * @author lzhang
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */

import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import shopping.CD;

public class ShoppingServlet extends HttpServlet {
  public void init(ServletConfig conf) throws ServletException  {
	super.init(conf);
  }
  public void doPost (HttpServletRequest req, HttpServletResponse res)
	  throws ServletException, IOException {
	HttpSession session = req.getSession(false);
	if (session == null) {
	  res.sendRedirect("http://localhost:8080/error.html");
	}
	Vector buylist=
//	  (Vector)session.getValue("shopping.shoppingcart");
	  (Vector)session.getAttribute("shopping.shoppingcart");
	String action = req.getParameter("action");
	if (!action.equals("CHECKOUT")) {
	  if (action.equals("DELETE")) {
		String del = req.getParameter("delindex");
		int d = (new Integer(del)).intValue();
		buylist.removeElementAt(d);
	  } else if (action.equals("ADD")) {
		//any previous buys of same cd?
		boolean match=false;
		CD aCD = getCD(req);
		if (buylist==null) {
		  //add first cd to the cart
		  buylist = new Vector(); //first order
		  buylist.addElement(aCD);
		} else { // not first buy
		  for (int i=0; i< buylist.size(); i++) {
			CD cd = (CD) buylist.elementAt(i);
			if (cd.getAlbum().equals(aCD.getAlbum())) {
			  cd.setQuantity(cd.getQuantity()+aCD.getQuantity());
			  buylist.setElementAt(cd,i);
			  match = true;
			} //end of if name matches
		  } // end of for
		  if (!match) 
			buylist.addElement(aCD);
		}
	  }
	  session.setAttribute("shopping.shoppingcart", buylist);
	  String url="/EShop.jsp";
	  ServletContext sc = getServletContext();
	  RequestDispatcher rd = sc.getRequestDispatcher(url);
	  rd.forward(req, res);
	} else if (action.equals("CHECKOUT"))  {
	  float total =0;
	  for (int i=0; i< buylist.size();i++) {
		CD anOrder = (CD) buylist.elementAt(i);
		float price= anOrder.getPrice();
		int qty = anOrder.getQuantity();
		total += (price * qty);
	  }
	  total += 0.005;
	  String amount = new Float(total).toString();
	  int n = amount.indexOf('.');
	  amount = amount.substring(0,n+3);
	  req.setAttribute("amount",amount);
	  String url="/Checkout.jsp";
	  ServletContext sc = getServletContext();
	  RequestDispatcher rd = sc.getRequestDispatcher(url);
	  rd.forward(req,res);
	}
  }
  private CD getCD(HttpServletRequest req) {
	//imagine if all this was in a scriptlet...ugly, eh?
	String myCd = req.getParameter("CD");
	String qty = req.getParameter("qty");
	StringTokenizer t = new StringTokenizer(myCd,"|");
	String album= t.nextToken();
	String artist = t.nextToken();
	String country = t.nextToken();
	String price = t.nextToken();
	price = price.replace('$',' ').trim();
	CD cd = new CD();
	cd.setAlbum(album);
	cd.setArtist(artist);
	cd.setCountry(country);
	cd.setPrice((new Float(price)).floatValue());
	cd.setQuantity((new Integer(qty)).intValue());
	return cd;
  }
}
--------------------------------

 


CD.java

-----------------------------------

/*
 * Created on Nov 13, 2003
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */

/**
 * @author lzhang
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package shopping;
public class CD {
  String album;
  String artist;
  String country;
  float price;
  int quantity;
  public CD() {
	album="";
	artist="";
	country="";
	price=0;
	quantity=0;
  }
  public void setAlbum(String title) {
	album=title;
  }
  public String getAlbum() {
	return album;
  }
  public void setArtist(String group) {
	artist=group;
  }
  public String getArtist() {
	return artist;
  }
  public void setCountry(String cty) {
	country=cty;
  }
  public String getCountry() {
	return country;
  }
  public void setPrice(float p) {
	price=p;
  }
  public float getPrice() {
	return price;
  }
  public void setQuantity(int q) {
	quantity=q;
  }
  public int getQuantity() {
	return quantity;
  }
}

---------------------------------