Can a JSP page access data in a Hashtable instead of a bean? If so, what is the syntax? For example, I want to put simple values into the Hashtable as well as more complex values such as other Hashtables or Vectors and retrieve them by key.
Created May 4, 2012
Govind Seshadri You can use just about any Java class within a JSP page. If the
class does not subscribe to JavaBean design patterns (i.e. has no getter/setter
methods for properties) it cannot be used
within the <jsp:getProperty> and <jsp:setProperty> tags, and has to be accessed only within scriptlets.
The following source code demonstrates the usage of Vector and Hashtable objects within JSP scriptlets:
Page1.jsp creates a Hashtable and initializes it with some data before placing it into the session:
<%@ page import="java.util.*"%> <html> <body> <jsp:useBean id="myHash" class="java.util.Hashtable" scope="session"> <% Hashtable numbers = new Hashtable(); numbers.put("one", new Integer(1)); numbers.put("two", new Integer(2)); numbers.put("three", new Integer(3)); Vector cities = new Vector(); cities.addElement("Paris"); cities.addElement("Venice"); cities.addElement("San Francisco"); myHash.put("numbers",numbers); myHash.put("cities",cities); %> </jsp:useBean> Placed hashtable within the session... </body> </html>
Page2.jsp extracts the previously instantiated Hashtable instance from the session and displays its contents:
<%@ page import="java.util.*"%> <html> <body> <jsp:useBean id="myHash" class="java.util.Hashtable" scope="session" /> Printing out the contents of Hashtable instance extracted from the session: <p> <% Hashtable newNumbers = (Hashtable)myHash.get("numbers"); if (newNumbers != null) { Enumeration e = newNumbers.keys(); Collection c = newNumbers.values(); Iterator i = c.iterator(); while (i.hasNext()) { Integer intValue = (Integer)i.next(); out.println(e.nextElement()+"="+ intValue.toString()+"<br>"); } } Vector newCities = (Vector)myHash.get("cities"); if (newCities != null) { out.println("<p>"); for (int i=0; i newCities.size();i++) out.println("newCities["+i+"]="+ newCities.elementAt(i)+"<br>"); } %> </body> </html>