Table of Contents
1. Introduction
1.1. What is JSP
1.2. How JSP Works?
1.3. Your First JSP Page
1.4. Advantages of JSP
1.5. JSP API
1.6. Life Cycle of a JSP Page
2. JSP Elements
2.1. JSP Page Structure
2.2. Comments
2.3. Scripting Elements
2.4. Implicit Objects
2.5. Directive Elements
2.6. Standard Action Tags
3. Using JSP
3.1. Maintaining State
3.2. Handling Error
3.3. Including Files (provide example)
3.4. Page Navigation (provide Examples)
3.5. Basic Form Processing
3.6. Accessing Database
4. Java Beans
4.1. Overview of JavaBeans
4.2. Using JavaBeans in JSP
4.3. Form Processing using Beans
4.4. Validating Form Data using Beans
5. JSP Application Models
5.1. Overview
5.2. Using Model 2
Chapter-1
Introduction
Objective: This chapter introduces Java Server Page Technology and
basic working of a JSP-based web application. After completing the
chapter, you will be able to develop your first JSP-based web application
and understand the role of JSP in a web application.
Java Server Pages (JSP) is a platform independent server-side Java technology that allows you to easily
create web pages supporting both static and dynamic contents. A JSP page is a text document that
contains static contents expressed in any txt-based format (such as HTML, XML), and dynamic contents
in form of JSP elements. The recommended file extension for the source file of a JSP page is .jsp.
You develop JSPs files that combine HTML elements, and embedded JSP elements to create
dynamic web pages. JSP elements are tag-based similar to HTML elements using which you insert pure
Java code in the webpage. JSP technology makes available all the dynamic capabilities of Java Servlet
technology but provides a more natural approach to creating static content.
The web server needs to have a JSP container to process JSP pages. A JSP container works with the web
server to provide the runtime environment and other services required by a JSP page. It interprets the
request and generates dynamic contents as per the JSP elements that are part of JSP pages. The working
of JSP technology can be explained using diagram given in Figure 1.1.
Subsequent invocations of the JSP file simply invoke the service() method of the servlet created by the
above process to serve the dynamic content to the web browser. The servlet produced as a result of the
above process remains in service until the application server is stopped, or the servlet is manually
unloaded. Figure 1.2 shows the above steps using a simple hello.jsp page.
When the browser requests to the JSP page, the JSP container checks to see whether a servlet for a JSP
file already exists and whether the modification date on the generated servlet is older than the JSP. If the
generated servlet is not older than its JSP, the JSP container assumes that the JSP hasn't changed and that
the generated servlet still matches the JSP's contents. In this case it simply invokes the service() method,
otherwise it follows the steps described above. This makes the process more efficient than with other
scripting languages (such as PHP) and therefore faster. So in a way, a JSP page is really just another way
to write a servlet without having to be a Java programming wizard. Except for the translation phase, a JSP
page is handled exactly like a regular servlet.
The first line of the JSP page contains a page directive which imports the java.util.Date class needed in
the page. In line 8, a JSP expression is embedded in the HTML element <h3> to display the current date
and time. Other lines are usual HTML tags need no explanation. This simple example shows how natural
and easy it is to mix static and dynamic contents in a JSP page.
The javax.servelt.jsp package which forms the core of the API has two important interfaces:
javax.servlet.jsp.JspPage and javax.servlet.jsp.HttpJspPage. The JspPage interface extends
javax.servlet.Servlet interface and describes the generic interaction that a JSP Page Implementation class
must satisfy. The interface defines a protocol with 3 methods; only two of them: jspInit() and
jspDestroy() are part of this interface as the signature of the third method: _jspService() depends on the
specific protocol used and is not part of it. The HttpJspPage interface that extends JspPage interface
describes the interaction using the HTTP protocol and defines _jspService() method as a part of it. A
class implementing this interface is responsible for invoking the above methods at the appropriate time
based on the corresponding Servlet-based method invocations. The jspInit() and jspDestroy() methods
can be defined by a JSP author, but the _jspService() method is defined automatically by the JSP
processor based on the contents of the JSP page. Figure 1.3 shows the inheritance hierarchy of these
important interfaces and methods defined by them are presented below.
Figure 1.3: Inheritance Hierarchy of HttpJspPage
When a request is mapped to a JSP page, the web container first checks whether the JSP pages servlet is
older than the JSP page. If the servlet is older, the web container translates the JSP page into a servlet
class and compiles the class. Otherwise it skips the translation and compilation.
After the page has been translated and compiled, the JSP pages servlet follows the Servlet Life Cycle:
1) If an instance of the JSP pages servlet does not exist, the container:
a) Loads the JSP pages servlet class
b) Instantiates an instance of the servlet class
c) Initializes the servlet instance by calling the jspInit() method
2) The container invokes the _jspService() method, passing request and response objects.
If the container needs to remove the JSP pages servlet, it calls the jspDestroy() method. The entire
request and response process has been shown in Figure 1.4.
JSP Elements
Objective: This chapter introduces the structural elements of JSP page
and their syntax using which you develop web pages. After completing
the chapter, you understand the structure of a JSP page and will be able
to develop simple web pages for your web application.
<html>
<body>
<h1>Only HTML</h1>
</body>
</html>
<%
String msg = "Only JSP script";
out.println("<html>");
out.println(" <body>");
out.println(" <h1>" + msg + "</h1>");
out.println(" </body>");
out.println("</html>");
%>
Example 2-1: A Sample JSP File with a mixture of JSP scripts and HTML tags
<%@ page contentType="text/html" %>
<% String msg = "A mix of JSP scripts and HTML tags;
%>
<html>
<body>
<h1><%= msg %></h1>
</body>
</html>
2.2 Comments
As you know comments in code is very helpful in understanding your code. You can use comments any
where you need in your JSP page using the following form:
<%-- JSP comments --%>
JSP comments are only seen in the JSP page. These comments are not included in the generated servlet
source code during translation phase, nor do they appear in the resultant HTML of the HTTP response.
You can also use HTML comments of the following form in addition to the JSP comments:
<!-- HTML Comment -->
However, unlike JSP comments, HTML comments are included in the generated servlet during page
translation and finally passed to the resultant HTML of the HTTP response.
Expressions
A JSP expression is used to insert values directly into the output. It has the following form:
<%= Java Expression %>
The expression is evaluated, converted to a string, and inserted in the resultant web page. This evaluation
is performed at run time (when the page is requested) and thus has full access to information about the
request. An expression tag can hold any Java language expression that can be used as an argument to
the out.print() method in the generated servlet. For example, an expression like <%= 20*45 %>
will appear as out.print(20*45) in the generated servlet source code. Expression can access the
implicit object (like request, response, session, out, etc.) and insert values in the web page directly.
Scriptlets
If you want to do something more complex than insert a simple expression, JSP scriptlets let you insert
arbitrary code into the generated servlets _jspService method. Scriptlets have the following form:
<% Any arbitrary Java Code %>
Scriptlets have access to the implicit objects. So, for example, if you want output to appear in the resultant
page, you would use the out variable, as in the following example.
<%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
In this particular instance, you could have accomplished the same effect more easily by using the
following JSP expression:
Attached GET data: <%= request.getQueryString() %>
In general, however, scriptlets can perform a number of tasks that cannot be accomplished with
expressions alone. These tasks include setting response headers and status codes, writing to the server log
or updating a database, or executing code that contains loops, conditionals, or other complex constructs.
For example, consider the following JSP fragment containing mixed of HTML text and scriptlets:
<% if (Math.random() < 0.5) { %>
Have a <b>nice</b> day!
<%} else {%>
Have a <b>lousy</b> day!
<% } %>
When converted to a servlet by the JSP engine, this fragment will result in something similar to the
following:
if (Math.random() < 0.5) {
out.println("Have a <b>nice</b> day!");
} else {
out.println("Have a <b>lousy</b> day!");
}
Declarations
A JSP declaration lets you define methods or fields that get inserted into the main body of the servlet
class (outside of the _jspService() method ). A declaration has the following form:
<%! Java Code %>
Since declarations do not generate any output, they are normally used in conjunction with JSP
expressions or scriptlets. For example, here is a JSP page that prints the number of times the current page
has been requested since the server was booted (or the servlet class was changed and reloaded).
<html>
<head>
<title>My First JSP Page</title>
</head>
<body>
<%! private int count = 0; %>
The count variable becomes a private attribute of the generated servlet when page translation is done.
Since JSP declarations result in code that appears outside of the _jspService() method, implicit object
these variables are not accessible in declarations.
out
This out variable is used to send output to the client. It has several methods which can be used for
properly formatting output message to the browser and for dealing with the buffer. Also note that out is
used almost exclusively in scriptlets, since JSP expressions are automatically placed in the output stream
and thus it rarely needs to refer to out explicitly.
request
This variable is the HttpServletRequest associated with the client request. It gives you access to
the request parameters, the request type (e.g. GET or POST), and the incoming HTTP headers (e.g.
cookies). You can use the request variable to retrieve the form data submitted by the user.
response
This variable is the HttpServletResponse associated with the response to the client. Note that since
the output stream (see out) is normally buffered, it is legal to set HTTP status codes and response headers
in JSP pages, even though the setting of headers or status codes is not permitted in servlets once any
output has been sent to the client.
session
This variable is the HttpSession object associated with the client request. Recall that sessions are
created automatically, so this variable is bound even if there is no incoming session reference. The one
exception is if you use the session attribute of the page directive to turn sessions off. In that case,
attempts to reference the session variable cause errors at the time the JSP page is translated into a
servlet.
application
This variable is the ServletContext as obtained via getServletConfig().getContext().
Servlets and JSP pages can store persistent data in the ServletContext object rather than in instance
variables. ServletContext has setAttribute() and getAttribute() methods that let you store
arbitrary data associated with specified keys. The difference between storing data in instance variables
and storing it in the ServletContext is that the ServletContext is shared by all servlets in the servlet
container (or in the Web application).
exception
This implicit object is of type Throwable and used in exception handling for displaying the error
messages. This object is only available to the JSP pages, which has isErrorPage set to true.
config
This variable is the ServletConfig object for a JSP page and mainly used for accessing configuration
information such as servlet context, servlet name, configuration parameters etc.
pageContext
JSP introduced a new class called javax.servlet.jsp.PageContext to give a single-point
access to many of the page attributes and to provide a convenient place to store shared data. The
pageContext variable stores the value of the PageContext object associated with the current page.
It is used for accessing page, request, application and session attributes.
page
This variable is simply a synonym for this reference variable of Java programming language and refers
to the current servlet instance (i.e. current page). It is not very useful in JSP. It was created as a place
holder for the time when the scripting language could be something other than Java.
2.5 Directive Elements
A JSP directive in a JSP page is a definition sent to the JSP engine and is valid to the JSP page. It gives
directions to the server regarding processing of the page. It contains directive name and optional list of
attribute-value pair separated by space to control the processing of the page. A directive appears at the
top of the JSP file before any other tags. Directives are of three types: Page, Include, and Taglib. The
syntax of a directive is:
<%@ directive_name [attribute_name=value ...] %>
Page Directives
The Page directive defines a number of page dependent properties which communicates with the web
container at the time of translation. You can place a page directive anywhere in the JSP file, but it is good
practice to make it as the first statement of the JSP page. You can define multiple attributes in a single
page directive or can have multiple page directives in a single JSP page. The most commonly used
attributes are explained below:
contentType: This attribute is used to set the content type and character set of the resultant web page.
The default value of contentType attribute is text/html; charset=ISO-8859-1. We can use it like below:
<%@ page contentType= text/html; charset=ISO-8859-1 %>
pageEncoding: We can set response encoding type with this page directive attribute, its default value is
ISO-8859-1. Example of it can be as follows:
<%@ page pageEncoding= UTF-8 %>
import: This is one of the most used page directive attribute. Its used to instruct container to import Java
packages while generating servlet code. This is similar to import statements in Java classes, interfaces.
An example of import page directive usage is:
<%@ page import="java.util.Date,java.util.List,java.io.*" %>
session: By default JSP page creates a session but sometimes we dont need session in JSP page. We can
use this attribute to indicate the container to not create session by default. Its default value is true and
session is created. To disable the session creation, we can use it like below.
<%@ page session= false %>
errorPage: This attribute is used to set the error page for the JSP page, if the JSP page throws exception,
the request is redirected to the error handler defined in this attribute. Its value is the URL of the error
handler page. For example:
<%@ page errorPage="errorHandler.jsp" %>
isErrorPage: This attribute is used to declare that current JSP page as an error page/ error handler for
another page throwing exceptions. Its default value is false. If its values is set to true then JSP implicit
object exception is available to the error page. For example;
<%@ page isErrorPage="true" %>
Include directive
JSP include directive is used to include the contents of another file to the current JSP page. The included
file can be HTML, JSP, text files etc. Include directive is very helpful in creating templates for user views
and break the pages into header, footer, sidebar sections. We can include any resource in the JSP page
like below:
<%@ include file="test.html" %>
The file attribute value should be the relative URI of the resource from the current JSP page.
Taglib directive
JSP taglib directive is used to define a tag library with prefix that we can use in JSP, we will look into
more details in JSP Custom Tags. We can define JSP tag libraries in like below;
<%@ taglib uri="/WEB-INF/c.tld" prefix="c"%>
JSP taglib directive is used in JSP standard tag libraries
Lab Exercises:
1. Write a JSP page to display a body color of the web page randomly from the colors of a rainbow.
Chapter-3
Using JSP
Objective: This chapter describes how-to handle some common
development tasks such as Maintaining State, Handling Errors,
Modularization, Page Navigation, Form Processing and Database
Accessing etc. After completing the chapter, you will be able to develop
basic web pages involving fundamental tasks for your web applications.
You know that HTTP is a static protocol. It has no built-in functionality to persist data from one request
to another. Once one request has been processed, the server picks up the next request with no prior
knowledge of the first request. Although this may provide performance benefits, it also presents a
problem with most web applications. Specifically, how can one part of the application make use of
previously entered data?
JSP technology provides access to a session object for you to store and retrieve keyed values at any given
time a user is interacting with the application. This session object is unique to each specific user and is
managed by the servlet container within the application server. The first time a user requests a JSP page,
the session is created on the server. This session has a session ID associated with it. This ID is passed
back and forth between the server and the user through an HTTP cookie. Each time the user requests a
JSP page, the session ID is passed along and therefore the appropriate session is associated with the user.
JSP technology provides access to a session object for you to store and retrieve keyed values at any given
time a user is interacting with the application. This session object is unique to each specific user and is
managed by the servlet container within the application server. The first time a user requests a JSP page,
the session is created on the server. This session has a session ID associated with it. This ID is passed
back and forth between the server and the user through an HTTP cookie. Each time the user requests a
JSP page, the session ID is passed along and therefore the appropriate session is associated with the user.
The session object is analogous to the HttpSession object used by servlets. The only real difference is that
the session object in a JSP is typically implicitly obtained and prepared for use. However, some JSP
environments might not automatically create the session for you. In that case, you need to obtain the
session by calling the getSession method of the request object. This will return an instance of
HttpSession. The only argument to this method is a Boolean value indicating whether to create a new
session if one doesn't already exist. This is an example of getting the session manually:
<% HttpSession session = request.getSession(true); %>
Once you have a session (in most cases it'll be an implicit object), it's possible to write, retrieve, and
remove attributes from the session object. These attributes are stored in much the same fashion as a
hashtable. Each value is associated with a named key. To write an attribute to the session, you would use
the setAttribute method as follows:
<% session.setAttribute("firstName", "Christina"); %>
The first argument is the attribute name. The second argument is the value of the attribute. This can be
any valid Java object. In this case it's a String object. To retrieve this value, you would use the
getAttribute method.
<% String fName = (String) session.getAttribute("firstName"); %>
Notice how you cast the result of this method to String. This is necessary because the session only stores
an object and returns an object without regard to the type of object it's storing. To remove this attribute,
you would use the removeAttribute method.
<% session.removeAttribute("firstName"); %>
Each of these methods can throw an IllegalStateException. This will occur if any of these methods are
called on an invalid session. A session will become invalid if the servlet has timed it out. The session
timeout property is configurable inside the servlet engine.
As an example, let's build a simple form that accepts a single field containing a person's name. You'll
submit this form to a JSP page that will store the name in the session and then present the user with two
simple hyperlinks to other JSP pages. Once the user goes to one of these pages, the name will be retrieved
from the session and a personalized message will appear. Example 3-1 shows this application.
Example 3-1: Using Session in JSP
File Name: sessionForm.jsp
<html>
<head><title>Session Example</title></head>
<body>
<center>
<h1>Session Example</h1>
<form action="sessionExample.jsp" method="post">
What is your name? <input type="Text" name="name"/><br><br>
<input type="Submit" value="submit"/>
</form>
</center>
</body>
</html>
<html>
<head><title>Session Example</title></head>
<body>
<%
String val = request.getParameter("name");
if (val != null)
session.setAttribute("name", val);
%>
<center>
<h1>Session Example</h1>
Where would you like to go?<br><br>
<a href="sessionExamplePage1.jsp">Page 1</a>
<a href="sessionExamplePage2.jsp">Page 2</a>
</body>
</html>
Fortunately, JSP has an elegant solution for error handling built in. Many developers never take
advantage of this feature and continue to code each exception handler individually. With JSP, you can
create a single page that will handle every uncaught exception in your system. If your JSP code throws an
exception not handled within a try-catch block, it'll forward the exception, and control, to a page you
specify using a JSP page directive.
<%= x / y %>
</body>
</html>
That's all on how-to define custom error page in Java application both page specific and an application
wide default error page. Important point to note is that page specific error pages takes precedence over
application wide default error page defined in web.xml.
In many applications, there are usually at least a few common page elements duplicated in many places.
These elements are typically page headers and footers, but they could also include elements such as
menus or even a piece of static or dynamic content presented in multiple pages. A problem arises when
these common elements are coded separately in multiple places. Not only is this a maintenance
nightmare, it also presents the possibility of errors or stale content (if one page gets updated while another
does not).
With JSP, you can organize your code so that common elements are stored in single files pulled in to
multiple JSP pages. It's a good design practice to put headers, menu bars, and footers in separate files. It
helps to standardize the look-and-feel of an application. It also makes it easy to build new pages. The
page designer can concentrate on the body of the page without regard to these common elements.
There are two choices for including files inside of a JSP page. You can include a page at compile-time or
at runtime. When including a file at compile-time, the file's contents are inserted into the JSP code before
it's compiled into a servlet. When including a file at runtime, the JSP page will not include the file until it
has been compiled and receives a request. When the servlet engine reaches the point of the page where
the included file is supposed to be, it'll execute the included page (or servlet) and insert the results in the
original page (as shown in Figure 3.1).
There are different ways to move from the current JSP page to another JSP page.
Using <jsp:forward>
You've seen with the <jsp:include> tag that it's possible to interrogate the request object, pass it on
to another page for processing, and insert the results inside of your original JSP. A similar tag is the
<jsp:forward> tag. The big difference between the two is that the forward tag never returns to the
original page (see Figure 3.2). It simply enables you to perform some processing with the request object
and pass it on to another page. These tags are the JSP equivalent of the RequestDispatcher interface
used in servlets to pass control from one servlet to another.
One thing to consider when using the forward tag is that when a request is forwarded to another JSP or
servlet, the current output buffer is cleared. Whatever may have been written to the output stream prior to
the forward tag will be ignored. Here's an example of how the forward tag might look:
<jsp:forward page="finalPage.jsp">
<jsp:param name="param1" value="10"/>
</jsp:forward>
Figure 3.2: Forward vs. include tags
Using sendRedirect()
You can use sendRedirect() method of HttpServletResponse object to redirect the user of the
current page to the another page. In this process the control of user is transferred from the current location
to another location using the specified URL and clears the buffer. Other location could be located on a
different server or different context. The signature of the method is:
public void sendRedirect(java.lang.String location)
SendRedirect() and <jsp:forward> approaches are still very useful while programming or working on any
web application using servlet or jsp. This is still a popular interview question, so now lets see some
difference between these two approaches (see Table 3.1).
Table 3.1: <jsp:forward> vs. sendRedirect()
<jsp:forward> SendRediret()
When we use forward method request is In case of sendRedirect request is transfer to
transfer to other resource within the same another resource within the same server or in a
server for further processing. different domain or different server for further
processing.
In case of forward web container handle all When you use SendRedirect(), web container
process internally and client or browser is not transfers the request to client or browser. So url
involved. Visually we are not able to see the given inside the sendRedirect method is
forwarded address in the browser address bar, visible as a new request to the client.
it is transparent.
In case of forward, we retain our old request In case of SendRedirect call, old request and
and response object on the new resource which response object is lost because its treated as
is going to process our request. So we use to new request by the browser. So parameters can
pass parameter using <jsp:param> tag. either be stored in user session or passed along
with the URL.
Because a <jsp:forward> operates within the SendRedirect() is slower because one extra
server, it executes faster than round trip is required because completely new
a sendRedirect() which requires round- request is created and old request object is lost.
trip communication with the client.
HTML forms are very common way of interaction between client and server in web applications. When
you submit a form, you pass data to the server. The browser uses two methods (e.g. GET and POST) to
pass this data to the web server. The form data which is a part of the HttpRequest is gathered in a JSP
page using the following methods of the request object similar to a servlet.
getParameter(): it is used to return a single value of a form parameter.
getParameterValues(): it is used to multiple values of a form parameter, for example a checkbox.
getParameterNames(): it is used to retrieve the complete list of parameters in the current request.
Form processing in JSP has two approaches: two-page approach and one-page approach. In a two-page
approach, the HTML form and the form handler are separated into two JSP files while both of them are
combined in a one-page approach. One benefit of this approach is that any data validation errors can be
displayed and highlighted along with the original form data. There are shown in Figure 3.3 and Figure 3.4
respectively.
The Example 3-4 demonstrates basic form processing using two-page approach in a JSP page without
implementing error handling and page navigation. It uses two files: simpleForm.jsp is the form file and
formHandler.jsp is the data processing file.
The Example 3-5 demonstrates basic form processing using one-page approach in a JSP page. It uses one
file, simpleHandler.jsp to display the HTML form as well as to process the form data.
Steps in JDBC
Working with JDBC isnt difficult. Depending on the task to be performed, you require four steps
(Figure 3.5 illustrates these four steps):
1. Load a JDBC driver for your database. This typically involves only a Class.forName()
statement specifying the driver class name.
2. Use that driver to open a connection to a particular database. This is done with a call to a static
getConnection(url) method to the DriverManager class. The url argument is in a
specific form know as connection string that indicates the driver type and the data source to use.
3. Issue SQL statements through the connection. Once the connection is established, it can be used
to create Statement objects through which SQL commands can be executed on the database.
4. Process result sets returned by the SQL operations. The ResultSet interface provides methods
to step through each row and get the values of each column.
Figure 3.5: Four steps involved in basic JDBC operations
Connection Strategy
Based on the life cycle of the JSP page, you have four strategies for making a database connection in a
JSP page. The differences between these strategies hinge on when the connection is made and on whether
connections are shared among requests to the other JSP pages. There are multiple strategies to it:
One-Per-Request connection
You load the JDBC driver in the jspInit() method, open a connection, carryout JDBC programming and
close that connection inside a scriptlet of the JSP page.
One-Per-Page connection
You use load the driver and open a connection in the jspInit() method, and then close that connection in
the jspDestroy( ) method in a JSP page. As a result, the JSP page uses one connection that remains open
during the entire lifetime of the JSP page and is shared by all users of the page.
One-Per-Session connection
You load the JDBC driver in the jspInit( ) method and store that connection in an HTTP Session object
inside a scriptlet of the JSP page. This will enable you to retrieve and use the connection in any other JSP
page during the same user session.
Consider a simple registration process. The user submit a registration form using a JSP file named
regForm.jsp which invokes register.jsp that collects the registration information, establishes a connection
with the database and tries to inserts the data submitted by the user in the login table of the database. If
the database insertion operation fails due to some reasons, then it redirects the response to regForm.jsp
displaying an error message Insertion Failed! Please try again! otherwise it redirects to logi.jsp that
displays Thank You for registering! message. The process is shown in Example 3-6.
Java Beans
Objective: This chapter introduces JavaBeans component and discusses
how-to handle form data and associated processing using JavaBeans.
After completing the chapter, you will be able to develop web
applications which leverage the benefits of JavaBeans.
Simple Property
For reading and writing the simple property, the bean must have a pair of methods of the following form:
public PropertyType getPropertyName() { }
public void setPropertyName(PropertyType value) { }
Indexed Property
An indexed property represents an array of values. For reading and writing the indexed property, the bean
must have a set of four methods. These methods are used to read/write a single value in the array as well
as the entire array of values of the bean based on situations. Thus, we can use additional get and set
methods that take an integer index parameter to read/write a single value in the array. This index
parameter indicates the place in the array where the new property value has to be accessed. The methods
are of the following form:
public PropertyType getPropertyName(int index);
public void setPropertyName(int index, PropertyType value);
public PropertyType[] getPropertyName();
public void setPropertyName(PropertyType[] value);
public SimpleBean() {
}
@Override
public String toString() {
return ("Hello "+firstName +
" " + lastName +
", <br>Welcome to the wonderful world of JavaBeans!");
}
}
<jsp:useBean id="beanName"
class="fully-qualified-classname" scope="bean-scope">
// other tags and scriptlets
</jsp:useBean>
Example:
<jsp:useBean id="simpleBean" scope="page"
class="jspbook.ch4.SimpleBean"/>
The <jsp:useBean> tag attempts to locate an instance of the Bean class. If no such object exists, the tag
causes a Bean object to be created. The second form of the syntax has a tag body which may contain tags
and scriptlets which are executed when the bean is instantiated. The id attribute gives the bean a name
that you can use to reference the bean throughout the JSP page. The class attribute specifies the actual
name of the bean class. It must be a fully qualified class name. Note that beans cannot be in the unnamed
package. Thus the format of the attribute value must be package-name.class-name. The scope attribute
defines the life of this bean. Valid options for this attribute are page, session, request, and
application. The page scope attribute tells the web container that this bean will remain for the life of
this particular page. As soon as the page is done executing, the bean disappears. The default scope is
page. If the bean has a scope of request, and then it gets stored in the request object and passed along
through the life of the request. In other words, if the page is forwarded to another page, then the bean can
be obtained through the request object. The session scope attribute tells the web container to store the
bean in the user's session object. It'll remain available throughout the life of that specific session. To make
a bean available to other JSP pages or Servlets, use the application scope attribute. This will store the
bean in the ServletContext object.
The first tag sets the value of the firstName property of the simpleBean JavaBean class. It does this by
explicitly setting the string value within the tag. Another option, as seen in the second tag, is to have the
property set automatically from the request parameters. The param attribute tells the bean which request
parameter populates the respective property. You can only use either the param attribute or the value
attribute. They cannot coexist within a single tag. If the bean property matches the request parameters,
then you can set one or all parameters automatically which is shown in 3rd option in the table. You can
also use an expression to assign value to a property as shown in 4th option.
To get a bean property, you would use the <jsp:getProperty> tag like this:
Syntax:
<jsp:getProperty name="beanName" property="propName"/>
Example:
<jsp:getProperty name="simpleBean" property="firstName"/>
When setting and getting properties from a JavaBean, type conversions are automatically performed for
all of the Java primitive data types and their corresponding wrapper classes. This makes it possible to set
numeric properties directly from String variables. It also enables the <jsp:getProperty> to return a
valid String to be inserted into the HTML content. Example 4-2 shows the use of SimpleBean in JSP page
Example 4-2: Use of JavaBean in JSP
<html>
<head>
<title>Hello Bean</title>
</head>
<body>
<jsp:useBean id="simpleBean"
scope="session" class="jspbook.ch4.SimpleBean">
<!-- Set bean properties -->
<jsp:setProperty
name="simpleBean" property="firstName" value="Ananta"/>
<jsp:setProperty
name="simpleBean" property="lastName" value="Ojha"/>
<jsp:useBean>
</body>
</html>
Processing web form may sound like a fairly easy task of passing request parameters and outputting a
response back to the client. However, with sophisticated web applications, this easy task quickly
becomes rather tedious as form processing involves multiple components operating in the background,
with each component responsible for a discrete task such as state management, data validation, database
access, and so on.
Processing web form is usually a two-stage process. First, you validate the content of the form fields to
ensure that it is valid and falls within the allowed limitations of the data structure. Second, you process
the form data according to the underlying application logic. The second stage occurs only after the first
stage is successful. This way ensures that the form data processing is performed only once and always
receives the right data.
Use of JavaBeans while submitting a web form is pretty helpful due to the following reasons:
Role Separation: By using JavaBeans, it allows you to move all processing code into the
JavaBeans separating the presentation logic in the JSP page that resembles HTML to the greatest
possible extent. This gives you clean and easily maintainable code in large programs such as e-
commerce while separating the web programmer from the web designer so that both carry out
their tasks easily, efficiently and independently. Further, the approach makes it easy for you to
provide different look and fees for the same web application by reusing the JavaBeans for
different presentations.
Automatic Data Population: When using JavaBeans for processing of form data, you can follow
a common design pattern by matching the names of bean properties with the names of the form
fields. In this way, you can direct the JSP engine to parse all the incoming values from the HTML
form fields that are part of the request object and to assign them to their corresponding bean
properties with a single statement, like the following:
<jsp:setProperty name="beanName" property="*"/>
This automatic population of bean properties with form data at runtime is possible through a
process called introspection, which lets a class expose its properties on request. The introspection
is managed by the JSP engine, and implemented via the Java reflection mechanism. This feature
alone can be a lifesaver when processing complex forms containing a significant number of input
elements.
Data Validation: Form data validation which is traditionally performed at the client-side using
JavaScript can be carried out more efficiently using JavaBeans at server-side. The server-side
validation is more secure as JavaScript based validation can be disabled maliciously at client-side.
Persisting Form Data: When use a JavaBeans with a form, the data can be persistent and used
across JSP pages as per need. You can redisplay the form to user with the submitted data in case
data validation fails, so that the user can correct error in invalid form fields without re-entering all
the form data from scratch.
Let us look at a case to understand the above facts. Consider a user registration process which is very
common in most of the web applications. The user submits a registration form; the application validates
the form data. If the validation succeeds then the application enters the user details into a back-end
database and displays a registration message to the user. Otherwise, the application displays the erroneous
data and asks the user to resubmit the form. The user enters into a loop and it continues till she submits
the correct data. The case not only implements validation but also implements all the points discussed
above. For easy understandability and brevity of code, we have considered a few of the registration
parameters and the registration form is provided in register.jsp (see Example 4-3).
Example 4-3: register.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>User Registration JSP</title>
</head>
<body>
<h3>User Registration</h3>
<form action="process.jsp" method="post">
User ID: <input type="text" name="userid"><br><br>
Password: <input type="password" name="password"><br><br>
Name: <input type="text" name="username"><br><br>
Email: <input type="text" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
When the registration form is submitted, it invokes process.jsp (see Example 4-4) file which simply
contains certain conditional logic to respond to the user action. It does not contain any presentation logic
and delegates the task of data validation and saving in a database to the JavaBeans component. So the
process.jsp which performs a controller job, first instantiates the JavaBean using the following action
tags:
<jsp:useBean id="userBean" class="bean.UserBean" scope="request">
<jsp:setProperty name="userBean" property="*"/>
</jsp:useBean>
The above tags ensure that when the bean is instantiated, the bean instance is populated with form data
automatically using bean introspection. For this purpose, the names of bean properties match with that of
form fields (see Example 4-5). Also, the scope of the bean is set to request in order to persist the form
data across multiple JSP pages. After creating the bean instance, the process.jsp calls the validate()
method of the bean to perform data validation task. If validation succeeds, it calls connectDB() and
saveUser() methods of the bean in a sequence to connect with the database and execute SQL command to
insert the user details into the database table. If the database operation succeeds, it returns non-zero and in
that case process.jsp chooses success.jsp (see Example 4-6) which in turn displays a success message
back to the user. If validation fails process.jsp chooses retry.jsp (see Example 4-7) which in turn re-
displays the registration form with errors messages and data submitted previously by the user.
Consequently the user is forced to enter correct data into the database. The bean uses a suitable data
structure to store and retrieve the error messages conveniently. Figure 4.1 summarizes this interaction.
Example 4-4: process.jsp
<%
if (userBean.validate()) {
userBean.connectDB();
int r= userBean.saveUser();
if(r>0){
%>
<jsp:forward page="success.jsp"/>
<%
}
} else {
%>
<jsp:forward page="retry.jsp"/>
<%
}
%>
import java.io.Serializable;
import java.util.HashMap;
import java.sql.*;
public UserBean() {
userid="";
password="";
username="";
email="";
errors = new HashMap();
}
5.1 Overview
The JSP specifications advocate two philosophical approaches for building applications using JSP
technology. These approaches, termed the JSP Model 1 and Model 2 architectures, differ essentially in
the location at which the bulk of the request processing is to be performed. In the Model 1 architecture,
shown in Figure 5.1, the JSP page alone is responsible for processing the incoming request and replying
back to the client. There is still separation of presentation from content, because all data access is
performed using beans.
Although the Model 1 architecture should be perfectly suitable for simple applications, it may not be
desirable for complex implementations. Indiscriminate usage of this architecture usually leads to a
significant amount of scriptlets or Java code embedded within the JSP page, especially if there is a
significant amount of request processing to be performed. While this may not seem to be much of a
problem for Java developers, it is certainly an issue if your JSP pages are created and maintained by
designers, which is usually the norm on large projects. Ultimately, it may even lead to an unclear
definition of roles and allocation of responsibilities, causing easily avoidable project-management
headaches.
The Model 2 architecture, shown in Figure 5.2, is a hybrid approach for serving dynamic content, since it
combines the use of both servlets and JSP. It takes advantage of the predominant strengths of both
technologies, using JSP to generate the presentation layer and servlets to perform process-intensive tasks.
Here, the servlet acts as the controller and is in charge of the request processing and the creation of any
beans or objects used by the JSP, as well as deciding, depending on the user's actions, which JSP page to
forward the request to. Note particularly that there is no processing logic within the JSP page itself; it is
simply responsible for retrieving any objects or beans that may have been previously created by the
servlet, and extracting the dynamic content from that servlet for insertion within static templates. Thus,
this approach typically results in the cleanest separation of presentation from content, leading to clear
delineation of the roles and responsibilities of the developers and page designers on your programming
team. In fact, the more complex your application, the greater the benefits of using the Model 2
architecture should be.
We shall implement this process using the Model2 architecture. However, we shall modify the model
slightly to accommodate the MVC (Model-View-Controller) design philosophy, so that it fits well to the
situation. The refined Model 2 architecture is shown in Figure 5.3. This refined model is more frequently
used than its original one.
When we, implement our registration process using this model, we use register.jsp (see Example 5-1) to
have the HTML form. It does not contain any JSP code. When the user submits the form, it invokes a
servlet (instead of a JSP) called RegisterServlet (see Example 5-2) which collect the form data, instantiate
a JavaBeans component named UserBean (see Example 5-3) and populate the instance using the form
data. The servlet which plays the role of a controller, delegates the tasks of data validation and databases
operations to the UserBean. It simply takes decision based on user actions. If the data validation succeeds,
the data is entered into the database and the servlet returns a registration success message using the
success.jsp file (see Example 5-4). Otherwise the servlet returns the HTML form using retry.jsp (see
Example 5-5) file which not only displays errors messages but also the data entered previously by the
user. With this approach, there is a clear separation of concerns. The JSP pages have pure presentation
logic in form of HTML or JSP tags and no Java code in it. The JavaBeans component holds the data and
data processing logic while the Servlet keeps the interaction control with it.
import bean.UserBean;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
userBean.setUserid(request.getParameter("userid"));
userBean.setPassword(request.getParameter("password"));
userBean.setUsername(request.getParameter("username"));
userBean.setEmail(request.getParameter("email"));
String url="";
if(userBean.validate()){
userBean.connectDB();
int r= userBean.saveUser();
if (r>0){
url="/success.jsp";
}
} else {
url="/retry.jsp";
}
RequestDispatcher
dispatcher=request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
package bean;
import java.io.Serializable;
import java.util.HashMap;
import java.sql.*;
public UserBean() {
userid="";
password="";
username="";
email="";
errors = new HashMap();
}
} catch (Exception e) { }
return r;
}
}
Lab Exercises: