480 likes | 615 Views
Week 6. JSP’s and JavaBean Page Scope JSP’s and JavaBean Request Scope JSP’s and JavaBean Session Scope JSP’s and JavaBean Application Scope A Shopping cart application using JSP and JavaBeans JSP and XML. Much of this lecture is from a nice little book entitled “Pure JSP” by Goodwill.
E N D
Week6 • JSP’s and JavaBean Page Scope • JSP’s and JavaBean Request Scope • JSP’s and JavaBean Session Scope • JSP’s and JavaBean Application Scope • A Shopping cart application using JSP and JavaBeans • JSP and XML Much of this lecture is from a nice little book entitled “Pure JSP” by Goodwill
Page Scope Beans with page scope are accessible only within the page where they were created. A bean with page-level scope is not persistent between requests or outside the page
Page Scope Example /* A simple bean that counts visits. Is found by jsp via the classpath*/ public class Counter { private int count = 1; public Counter() {} public int getCount() { return count++; } public void setCount(int c) { count = c; } }
<%-- Use the Counter bean with page scope. --%> <jsp:useBean id = "ctr" scope = "page" class = "Counter" /> <html> <head> <title>Page Bean Example</title> </head> <body> <h3>Page Bean Example </h3> <center> <b>The current count for the counter bean is: </b> <jsp:expression> ctr.getCount() </jsp:expression> </center> </body> </html>
Request Scope • One page may call another and the bean is still available. • When the current request is complete the bean is reclaimed • by the JVM.
Request Scope Example <%-- Use the Counter bean with request scope. --%> <%@ page errorPage = "errorpage.jsp" %> <jsp:useBean id = "ctr" scope = "request" class = "Counter" /> <html> <head> <title>Request Bean Example</title> </head> <body> <h3>Request Bean Example </h3>
<center> <b>Calling another page ... to see if the bean is still there </b> <jsp:scriptlet> ctr.setCount(10); </jsp:scriptlet> </center> <jsp:forward page = "RequestBean2.jsp" /> </body> </html>
<%-- Use the Counter bean with request scope. --%> <%@ page errorPage = "errorpage.jsp" %> <%@ page import = "java.util.*" %> <jsp:useBean id = "ctr" scope = "request" class = "Counter" /> <html> <head> <title>Request Bean Example Number 2</title> </head>
<body> <h3>Request Bean Example Number 2</h3> <center> <b>The current count for the counter bean is: </b> <jsp:expression> ctr.getCount() </jsp:expression> <p> <jsp:expression> new Date() </jsp:expression> </center> </body> </html>
Looks like first page hit. Bean holds its value Time changes on each hit but 10 stays. Unknown
Session Scope Beans with session scope are accessible within pages processing requests that are in the same session as the one in which the bean was created. Session lifetime is typically configurable and is controlled by the servlet container (in our case, Jigsaw). When the same browser is used, you get the same session bean.
Session Scope Example <%-- Use the Counter bean with session scope. --%> <%@ page errorPage = "errorpage.jsp" %> <jsp:useBean id = "ctr" scope = "session" class = "Counter" /> <html> <head> <title>Session Bean Example 1</title> </head> <body> <h3>Session Bean Example 1</h3> <center> <b>The current count for the counter bean is: </b> <jsp:expression> ctr.getCount() </jsp:expression> </center> </body> </html>
The counter increments on each hit. Netscape visits 16 times.
Application Beans A bean with a scope value of application has an even broader and further reaching availability than session beans. Application beans exist throughout the life of the JSP container itself, meaning they are not reclaimed until the server is shut down. Session beans are available on subsequent requests from the same browser. Application beans are shared by all users.
Application Bean Example 1 <%-- Use the Counter bean with application scope. --%> <%@ page errorPage = "errorpage.jsp" %> <jsp:useBean id = "ctr" scope = "application" class = "Counter" /> <html> <head> <title>Application Bean Example 1</title> </head> <body> <h3>Application Bean Example 1</h3> <center> <b>The current count for the counter bean is: </b> <jsp:expression> ctr.getCount() </jsp:expression> </center> </body> </html>
Application Bean Example 2 <%-- Use the Counter bean with application scope. --%> <%-- applicationbean2.jsp --%> <%@ page errorPage = "errorpage.jsp" %> <%@ page import = "java.util.*" %> <jsp:useBean id = "ctr" scope = "application" class = "Counter" /> <html> <head> <title>Application Bean Example Number 2</title> </head>
<body> <h3>Application Bean Example Number 2</h3> <center> <b>We have had </b> <jsp:expression> ctr.getCount() </jsp:expression> <p> <b> total visitors. </b> </center> </body> </html>
And then later to applicationbean2.jsp from a different machine using Netscape…
A Shopping Cart AddToShoppingCart.jsp
The Bean – ShoppingCart.java // ShopingCart.java import java.util.*; public class ShoppingCart { protected Hashtable items = new Hashtable(); public ShoppingCart() {}
public void addItem(String itemId, String description, float price, int quantity) { // pack the item as an array of Strings String item[] = { itemId, description, Float.toString(price), Integer.toString(quantity)}; // if item not yet in table then add it if(! items.containsKey(itemId)) { items.put(itemId, item); } else { // the item is in the table already String tempItem[] = (String[])items.get(itemId); int tempQuant = Integer.parseInt(tempItem[3]); quantity += tempQuant; tempItem[3] = Integer.toString(quantity); } }
public void removeItem(String itemId) { if(items.containsKey(itemId)) { items.remove(itemId); } } public void updateQuantity(String itemId, int quantity) { if(items.containsKey(itemId)) { String[] tempItem = (String[]) items.get(itemId); tempItem[3] = Integer.toString(quantity); } } public Enumeration getEnumeration() { return items.elements(); }
public float getCost() { Enumeration enum = items.elements(); String[] tempItem; float totalCost = 0.00f; while(enum.hasMoreElements()) { tempItem = (String[]) enum.nextElement(); totalCost += (Integer.parseInt(tempItem[3]) * Float.parseFloat(tempItem[2])); } return totalCost; }
public int getNumOfItems() { Enumeration enum = items.elements(); String tempItem[]; int numOfItems = 0; while(enum.hasMoreElements()) { tempItem = (String[]) enum.nextElement(); numOfItems += Integer.parseInt(tempItem[3]); } return numOfItems; }
public static void main(String a[]) { ShoppingCart cart = new ShoppingCart(); cart.addItem("A123", "Bike", (float)432.46, 10); cart.addItem("A124", "Bike", (float)732.46, 5); System.out.println(cart.getNumOfItems()); System.out.println(cart.getCost()); cart.updateQuantity("A123", 2); System.out.println(cart.getNumOfItems()); cart.addItem("A123", "Bike", (float)432.46, 4); System.out.println(cart.getNumOfItems()); } } C:\Jigsaw\Jigsaw\Jigsaw\WWW\beans>java ShoppingCart 15 7986.9004 7 11
AddToShoppingCart.jsp <%@ page errorPage = "errorpage.jsp" %> <jsp:useBean id = "cart" scope = "session" class = "ShoppingCart" /> <html> <head> <title>DVD Catalog </title> </head>
<jsp:scriptlet> String id = request.getParameter("id"); if(id != null) { String desc = request.getParameter("desc"); Float price = new Float(request.getParameter("price")); cart.addItem(id, desc, price.floatValue(), 1); } </jsp:scriptlet> <a href = "ShoppingCart.jsp"> Shopping Cart Quantity </a> <jsp:expression> cart.getNumOfItems() </jsp:expression> <hr>
<center> <h3> DVD Catalog </h3> </center> <table border = "1" width = "300" cellspacing = "0" cellpadding = "2" align = "center" > <tr> <th> Description </th> <th> Price </th> </tr>
<tr> <form action = "AddToShoppingCart.jsp" method = "post" > <td>Happy Gilmore</td> <td>$19.95</td> <td> <input type = "submit" name = "submit" value = "add"> </td> <input type = "hidden" name = "id" value = "1" > <input type = "hidden" name = "desc" value = "Happy Gilmore" > <input type = "hidden" name = "price" value = "10.95" > </form> </tr>
<tr> <form action = "AddToShoppingCart.jsp" method = "post" > <td>Brassed Off Full Monty</td> <td>$23.99</td> <td> <input type = "submit" name = "submit" value = "add"> </td> <input type = "hidden" name = "id" value = "2" > <input type = "hidden" name = "desc" value = "Brassed Off Full Monty" > <input type = "hidden" name = "price" value = "12.99" > </form> </tr>
<form action = "AddToShoppingCart.jsp" method = "post" > <td>FlashDance</td> <td>$12.95</td> <td> <input type = "submit" name = "submit" value = "add"> </td> <input type = "hidden" name = "id" value = "3" > <input type = "hidden" name = "desc" value = "FlashDance" > <input type = "hidden" name = "price" value = "17.05" > </form> </tr> </table> </body> <html> h
ShoppingCart.jsp <%@ page errorPage = "errorpage.jsp" %> <%@ page import = "java.util.*" %> <jsp:useBean id = "cart" scope = "session" class = "ShoppingCart" /> <html> <head> <title> Shopping Cart Contents </title> </head>
<body> <center> <table width = "300" border = "1" cellspacing = "0" cellpadding = "2" border = "0" > <caption> <b> Shopping Cart Contents </b> </caption> <tr> <th> Description </th> <th> Price </th> <th> Quantity </th> </tr>
<jsp:scriptlet> Enumeration enum = cart.getEnumeration(); String tempItem[]; while(enum.hasMoreElements()) { tempItem = (String[]) enum.nextElement(); </jsp:scriptlet>
<tr> <td> <jsp:expression> tempItem[1] </jsp:expression> </td> <td align = "center"> <jsp:expression> "$" + tempItem[2] </jsp:expression> </td> <td align = "center"> <jsp:expression> tempItem[3] </jsp:expression> </td> </tr>
<jsp:scriptlet> } </jsp:scriptlet> </table> </center> <a href = "AddToShoppingCart.jsp">Back to Catalog </a> </body> </html>
JSP and XML item.xml <?xml version = "1.0" ?> <item> <id>33445</id> <description>The Art of Computer Programming Vol. 1 </description> <price>34.95</price> <quantity>56</quantity> </item>
A SAX Handler import java.io.*; import java.util.Hashtable; import org.xml.sax.*; public class SAXHandler extends HandlerBase { private Hashtable table = new Hashtable(); private String currentElement = null; private String currentValue = null; public void setTable(Hashtable table) { this.table = table; }
public Hashtable getTable() { return table; } public void startElement(String tag, AttributeList attrs) throws SAXException { currentElement = tag; } public void characters(char ch[], int start, int length) throws SAXException { currentValue = new String(ch,start,length); } public void endElement(String name) throws SAXException { if(currentElement.equals(name)) { table.put(currentElement, currentValue); } } }
XMLExample.jsp <html> <head> <title>JSP XML Example </title> </head> <body> <%@ page import="java.io.*" %> <%@ page import="java.util.Hashtable" %> <%@ page import="org.w3c.dom.*" %> <%@ page import="org.xml.sax.*" %> <%@ page import="javax.xml.parsers.SAXParserFactory" %> <%@ page import="javax.xml.parsers.SAXParser" %> <%@ page import="SAXHandler" %>
<jsp:scriptlet> File file = new File("c:\\Jigsaw\\Jigsaw\\Jigsaw\\Www\\fpml\\item.xml"); FileReader reader = new FileReader(file); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); SAXHandler handler = new SAXHandler(); sp.parse(new InputSource(reader), handler); // Parse Hashtable cfgTable = handler.getTable(); //After all the parsing </jsp:scriptlet>
<table align="center" width="600"> <caption>XML Item From JSP</caption> <jsp:scriptlet> // Print the config settings that we are insterested in. out.println("<tr><td align=\"left\">ID</td>" + "<td align=\"center\">" + (String)cfgTable.get(new String("id")) + "</td></tr>"); out.println("<tr><td align=\"left\">DESCRIPTION</td>" + "<td align=\"center\">" + (String)cfgTable.get(new String("description")) + "</td></tr>"); out.println("<tr><td align=\"left\">PRICE</td>" + "<td align=\"center\">" + (String)cfgTable.get(new String("price")) + "</td></tr>"); System.out.println("<tr><td align=\"left\">QUANTITY</td>" + "<td align=\"center\">" + (String)cfgTable.get(new String("quantity")) + "</td></tr>"); </jsp:scriptlet>
</table> </body> </html>