In part one (
Start serving Java Server Pages: Introduction
), we introduced Java Server Pages and showed some simple examples. Hopefully, you were able to appreciate some of the benefits of JSP and how it simplifies Web application development.
In this article, we are going to introduce a couple of other features of JSP. First, we take a look at session management. Next, we examine how JavaBeans can be used in the context of JSP and see how this integration enhances application development.
Session object
One of the problems faced by Web application developers is maintaining state. Methods like cookies, hidden text fields in HTML forms, and appending state information to the URL have been used. Java servlets provide a natural “session” object that stays alive as part of the servlet. Session or state information can be stored and retrieved to/from this object. JSP takes the same approach (so if you know servlets, this should be very familiar to you). If you take a look at the quick JSP guide from Sun, you’ll notice a few implicit objects (where you don’t have to explicitly declare or instantiate them). One of these objects is the request object, which is a subclass of HttpServletRequest. This object contains all the information about the current request from the browser, including cookies, HTML form variables, etc.
Another implicit object is the session object which is where our interest lies. This object is created when the first JSP page is hit and is associated with the request object. The session object is useful for applications where several pages must be navigated in order to perform a transaction. A shopping cart would be a good example.
In order to demonstrate usage of the session object we have created three pages (to simulate a multi-page application). The first page (q1.html) is a simple HTML page that displays a form asking for a name. Here is the first page:
<HTML> <HEAD> <TITLE> First Page </TITLE> </HEAD> <BODY> <FORM METHOD=POST ACTION="q2.jsp"> What is your name? <INPUT TYPE=TEXT NAME="thename"> <P> <INPUT TYPE=SUBMIT VALUE="SUBMIT"> </FORM> </BODY> </HTML> |
The second page is a JSP page (q2.jsp). It uses the request object to retrieve the value of the name text field from the HTML form and stores that in the “name” variable. It will then place that value in the session object. The session object is a collection of name/value pairs. In this case, the name is “thename” and the value is what is stored in “name.” Since the session object stays alive, the values stored in it will be available to subsequent pages. This page also paints another HTML form asking for one’s favorite food. Here is the listing for the second page:
<HTML> <HEAD> <TITLE> Page 2 </TITLE> </HEAD> <BODY> <%@ page language="java" %> <%! String name=""; %> <% name = request.getParameter("thename"); session.putValue("thename", name); %> The name is <%= name %> <p> <FORM METHOD=POST ACTION="q3.jsp"> What is your favorite food? <INPUT TYPE=TEXT NAME="food"> <P> <INPUT TYPE=SUBMIT VALUE="SUBMIT"> </FORM> </BODY> </HTML> |
The third page is also a JSP page and basically is a result page. It retrieves the name value from the session object and displays it. Recall that that value was entered two pages ago and its value would not have carried over automatically were it not for the session object. It also retrieves the value of favorite food from the previous page. Both values are then displayed. Here is the code listing for the third page:
<HTML> <HEAD> <TITLE> Page 3 </TITLE> </HEAD> <BODY> <%@ page language="java" %> <%! String food=""; %> <% food = request.getParameter("food"); String name = (String) session.getValue("thename"); %> Your name is <b><%= name %></b> <P> Your favorite food is <b><%= food %></b> </BODY> </HTML> |
Mixing Beans and JSP
JavaBeans is a component model based on Java. Numerous texts have been written on JavaBeans and the benefits of using a component model. JSP provides a clean integration between Web applications and non-visual components. Aside from streamlining the development process (where tested and trusted components can be used instead of redeveloping code), this integration provides great flexibility in JSP applications. The components could perform complex calculations or handle database connectivity and data retrieval. The components could also be used as a mean to mix and match data from various sources to create a Web page. If you have three components that display news, stock quotes and weather information respectively, the task of creating a page containing all three types of data would be as simple as instantiating three Beans and placing them next to each other using HTML tables. JSP simplifies this sort of localization, personalization, and application integration.
To demonstrate usage of JavaBeans within the context of a JSP we have created a TaxRate Bean. It has two properties: State and Rate. The setter methods are used to set the two properties and the getter methods are used to retrieve the properties. Normally, this Bean would be implemented as a look-up Bean where the rates are retrieved from a database table. We have simplified this by allowing you (the taxpayer) to arbitrary set the tax rate for a given state! Here is the code for our Bean:
package tax; public class TaxRate { String State; double Rate; public TaxRate() { this.State = "NY"; this.Rate = 8.5; } public void setState (String stateName) { this.State = stateName; } public String getState() { return (this.State); } public void setRate (double rateValue) { this.Rate = rateValue; } public double getRate () { return (this.Rate); } } |
In order to use the Bean in our JSP page, we use the <jsp:useBean> tag. It first searches for a bean instance that matches the scope and class. If it can’t find one, it will instantiate the named class. Depending on what JSP engine you are using, there may be specific instructions on where and how to deploy the Bean to be accessible to the JSP page. In our case, we have placed the .class file representing the Bean in the following directory: c:jswdk-1.0examplesWEB-INFjspbeanstax
Note that we created a separate directory (i.e., tax) for this application. Once you compile the Bean, place it in the appropriate directory.
We are now ready to actually use the Bean in the JSP page. Here is the code, and you can place the JSP code in its own directory, where you have placed your other JSP pages:
<HTML> <HEAD> <TITLE> Tax Rate </TITLE> </HEAD> <BODY> <%@ page language="java" %> <jsp:useBean id="taxbean" scope="application" class="tax.TaxRate" /> <% taxbean.setState("NJ"); taxbean.setRate(6.5); %> <b> Using method 1:</b> <p> State is: <%= taxbean.getState() %> <br> Rate is: <%= taxbean.getRate() %> <p> <% taxbean.setState("TX"); taxbean.setRate(5.5); %> <b> Using method 2:</b> <p> State is: <jsp:getProperty name="taxbean" property="State" /> <br> Rate is: <jsp:getProperty name="taxbean" property="Rate" /> </BODY> </HTML> |
Within the <jsp:useBean>, there are several attributes. The id attribute is used to identify the Bean throughout the JSP page. The scope attribute indicates how long the Bean should stay alive. Finally the class attribute indicates the class file representing the Bean (prepended by its package name).
We use the “setter” methods of the Bean to set its properties and use the “getter” methods to retrieve its properties. We have also shown a second method for retrieving the properties of the Bean and that is using the <jsp:getProperty> tag. The name attribute refers to the name of the Bean as indicated with the id attribute. The property attribute specifies the attribute whose value we need. Also note that for the <jsp:useBean> and <jsp:getProperty> tags, we used the short notation of /> to close the tag instead of the usual </jsp:useBean> and </jsp:getProperty>.
Conclusions
JSP is based on servlet technology and servlets have proven themselves as a viable framework for development of Web applications. JSP pages look like HTML but with Java code embedded in them. With a good design, where most of the logic is contained within JavaBeans, it is possible to utilize your existing pool of HTML programmers to create highly dynamic and data-driven pages. This will allow for a clear separation of business logic and its presentation.
About the author
Piroz Mohseni is president of Bita Technologies, focusing on business improvement through effective usage of technology. His area of interests include enterprise Java, XML, and e-commerce applications. Contact him at pmohseni@iname.com.