Anda di halaman 1dari 56

JSP Made Easy

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.

1.1 What is JSP?

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.

1.2 How JSP Works

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.

Figure 1.1: Working of JSP Technology


Following are the steps involved wherein a web server generates web pages in a JSP based web
application.
1. As with the any other web page, the web browser makes an HTTP request to a JSP page in the
web server.
2. The web server recognizes that the request is for a JSP page and forwards it to the JSP container.
3. The JSP container converts the JSP page into an equivalent Servlet which is a pure Java source
file. The generated JSP Servlet is responsible for rendering dynamic contents.
4. The JSP container compiles the JSP Servlet source code into a Servlet class file.
5. The container creates an instance of the JSP Servlet class. The init() and service() methods of
the Servlet are called in sequence to generate a dynamic HTML page as per the original JSP
page. The HTML page is handed over to the web server.
6. The web server forwards the HTML page as the HTTP response to the browser which makes
usual page rendering.

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.

Figure 1.2: Processing steps for hello.jsp

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.

1.3 Your First JSP Page


Before you learn all about JSP, let us look at a very simple JSP page to say Hello and display todays
date and time to start with. The JSP page is shown in Example 1.1.
Example 1.1: hello.jsp
1 <%@page import="java.util.Date"%>
2 <!DOCTYPE html>
3 <html>
4 <head>
5 <title>First JSP Page</title>
6 </head>
7 <body>
8 <h3>Hello! Today is <%= new Date()%></h3>
9 </body>
10 </html>

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.

1.4 Advantages of JSP


There are many advantages of JSP over servlets and other server-side technologies. Some of these are
outline below:
Platform Independence and Portable: JSP technology is platform independent and portable as
it is based on Java technology.
Power of Java: Since Java code can be embedded in JSP pages, it brings the full power of Java
to JSP pages.
Performance: Since a JSP page is converted to an equivalent Servlet, it offers increased
performance like a servlet when requested by the client.
Easy Learning: JSP is tag based and requires no strong background of Java language. A tag-
based programming approach facilitates a non-Java programmer to easily learn and develop web
application using JSP. Even a web designer can put small interactive code with static HTML.
Easy Deployment: JSP needs no compilation by the developer. Developers deploy directly a
JSP source file in server and use it. However, in case of servlets, developers compile it manually
and deploy the class file in the server for use.
Separation Static and Dynamic Content: JSP enables separation of static content from
dynamic content. As a result, the roles of page design and programming are nicely separated.
Separation of Presentation Logic: JSP facilitates separation of presentation logic from
business logic through the use of Java Bean components. Java Beans are easily integrated into
JSP pages using JSP Action tags.
Use of Implicit Objects: Unlike servlets, you do not need to create objects or get a reference of
PrintWriter, HttpSession, RequestDispatcher, ServletConfig, ServletContext etc. These objects
are available to you by the JSP container and you use them directly. This decreases lot of coding.
Extensible: JSP can be extended using custom tag. Custom tag library enhances its power and
meets ad-hoc and specific requirements of applications.

1.5 JSP API


The JSP API consists of three packages: javax.servlet.jsp, javax.servlet.jsp.tagext, and
javax.servlet.jsp.el. The javax.servlet.jsp package provides Classes and interfaces for the Core JSP API.
The javax.servlet.jsp.tagext package provides Classes and interfaces for the definition of Java Server
Pages Tag Libraries. The javax.servlet.jsp.el package provides Classes and interfaces for the JSP
Expression Language API.

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

public void jspInit()


It is invoked only once during the life cycle of the JSP when JSP page is requested for the first
time. It is used to perform initialization. A JSP page can override this method by including a definition for
it in a declaration element.
public void jspDestroy()
It is invoked only once during the life cycle of the JSP before the JSP page is destroyed. It can be
used to perform some cleanup operation. A JSP page can override this method by including a definition
for it in a declaration element.
public void _jspService(
javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response ) throws
javax.servlet.ServletException, java.io.IOException
It is invoked each time when request for the JSP page comes to the container. It is used to process
the request. The method corresponds to the body of the JSP page. This method is defined automatically
by the JSP container and should never be defined by the JSP page author.

1.6 Life Cycle of a JSP page


A JSP page services requests as a servlet. Thus, the life cycle and many of the capabilities of JSP pages
(in particular the dynamic aspects) are determined by Java Servlet technology. The following are the steps
followed in the life cycle of a JSP page.
1. Translation
2. Compilation
3. Loading
4. Instantiation
5. Initialization
6. Request Processing
7. Destruction

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.

Figure 1.4: JSP Page Life Cycle


Lab Exercises:
Chapter-2

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.

2.1 JSP Page Structure


The content structure of a basic JSP file is straightforward. The first line of a JSP file contains a page
directive, which indicates that this is a Java server page that outputs HTML text:
<%@ page contentType="text/html" %>
The rest of the file contains more or less whatever you want. You can write:
only HTML tags
only JSP scripts
a mixture of JSP scripts with HTML tags
Let us have a look at these JSP files variants provided in Example 2-1, Example 2-2 and Example 2-3.
Example 2-1: A Sample JSP File with only HTML tags
<%@ page contentType="text/html" %>

<html>
<body>
<h1>Only HTML</h1>
</body>
</html>

Example 2-1: A Sample JSP File with only JSP scripts


<%@ page contentType="text/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.

2.3 Scripting Elements


JSP scripting elements let you insert Java code into the JSP page. These elements are kept inside <% %>
tags. Scripting elements are processed by the JSP engine during translation of the JSP page and the Java
code is inserted into the generated servlet from the JSP page. Primarily they are of three forms:
Declaration, Expressions and Scriptlets. Each of these scripting elements is described in more detail here.

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; %>

Page Count is:


<% out.println(++count); %>
</body>
</html>

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.

2.4 Implicit Objects


To simplify code in JSP expressions and scriptlets, you are supplied with some automatically defined
variables, called implicit objects. They represent some commonly used objects of Servlet Technology
that JSP page developers might need to use. For example you can retrieve HTML form parameter data by
using request variable, which represent the HttpServletRequest object as in Figure 2-1

Figure 2-1: Example of Implicit Object and its use


As shown in the example, they need no declaration and initialization. There are total 9 implicit objects
available in JSP: request, response, out, session, application, exception, config, pageContext, and page.
All these objects and corresponding class are given in Table 2.1. Further each one of them is introduced
below.
Table 2.1: Implicit Objects and their Corresponding Classes
Object Variable Class Name
out javax.servlet.jsp.JspWriter
request javax.servlet.http.HttpServletRequest
response javax.servlet.http.HttpServletResponse
session javax.servlet.http.HttpSession
application javax.servlet.ServletContext
exception javax.servlet.jsp.JspException
config javax.servlet.ServletConfig
pageContext javax.servlet.jsp.PageContext
page java.lang.Object

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

2.5 Standard Action Tags


JSP provides a bunch of standard action tags that we can use for specific tasks such as working with Java
bean objects, including other resource, forward the request to other resource etc. These tags are used to
remove or eliminate Java code directly inside your JSP page. A list of most popular standard JSP action
elements are given in Table 2.2. We will discuss detail use of these elements later on.
Table 2.2: A list of Popular Action Tags

JSP Action Description

<jsp:useBean> To get the Java bean object from given scope or to


create a new instance of the Java bean.

<jsp:getProperty> To get the property of a Java bean, used with


<jsp:useBean>action.

<jsp:setProperty> To set the property of a Java bean object, used with


<jsp:useBean> action.

<jsp:forward> To forward the request to another resource.

<jsp:include> To include a resource at runtime, can be HTML, JSP or


any other file

<jsp:param> To add parameters to request, used with


<jsp:forward> or <jsp:include> actions

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.

3.1 Maintaining State

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>

File Name: sessionExample.jsp

<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>

File Name: sessionExamplePage1.jsp


<html>
<head><title>Session Example</title></head>
<body>
<center>
<h1>Session Example</h1>
Hello, <%= session.getAttribute("name") %>. Welcome to Page 1!
</body>
</html>

File Name: sessionExamplePage2.jsp


<html>
<head><title>Session Example</title></head>
<body>
<center>
<h1>Session Example</h1>
Hello, <%= session.getAttribute("name") %>. Welcome to Page 2!
</body>
</html>

3.2 Handling Errors

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.

Creating an Error Page


As previously mentioned, an error page should take an exception, report it to a system administrator, and
display a meaningful message to the user. The first thing you need to do, however, is declare that the page
to be used is an error page. You do this using the isErrorPage page directive as follows:
<%@ page isErrorPage="true" %>
When reporting the error, it's sometimes helpful to pass in the name of the page in which the error
occurred. As the error is being reported in a shared error page, without this information, the administrator
would have a difficult time figuring out where the problem occurred. To retrieve the name of the page,
you use the getParameter() method of the request object.
<% String from = (String) request.getParameter("from"); %>
The exception object is another implicit JSP object that does not need to be declared or instantiated. It's
only available to those pages that have been designated as error pages. It'll report whatever the uncaught
exception was that caused the error page to be called. For your purposes, you'll make use of the toString()
method of the exception object. Remember, when using a JSP expression, the toString() method is called
implicitly to convert the value of the object to a String. Example3-2 shows a simple error page displaying
uncaught error.

Example 3-2: myErrorPage.jsp


<%@ page isErrorPage="true" %>
<html>
<head>
<title>A JSP page handling Error!</title>
</head>
<body>
<br>
<% String from = (String)request.getParameter("from"); %>
An error occurred on page <b><%= from %></b>.
<br><br>
The exception was:
<br>
<b><%= exception %></b>
<!-- Send exception report to administrator -->
<% System.out.println(exception.toString()); %>
</body>
</html>
Forwarding Errors
Now that you've created an error page, you need to code your pages to forward all uncaught exceptions to
it. You do this by adding the JSP page directive errorPage. Each page (as shown in Example 3-3) you
want to forward errors from needs this directive included. As you'll know, the error page is expecting a
parameter named from to determine which page called the error page. Here's a look at the page directive:
<%@ page errorPage="myErrorPage.jsp?from=simpleError.jsp" %>

Example 3-3: simpleError.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<%@ page errorPage="myErrorPage.jsp?from=simpleError.jsp" %>


<!DOCTYPE html>
<html>
<head>
<title>A JSP Page throwing Error!</title>
</head>
<body>
<%!
int x = 10;
int y = 0;
%>

<%= x / y %>
</body>
</html>

In the code shown in Example 3-3, an ArithmeticException causes an unhandled exception to be


thrown. This results in a request being forwarded to myErrorPage.jsp.

Application-Wide Error Page


There is another way to define error pages in java web application written using servlet and JSP. This is
called application wide error page or default/general error page because its applicable to whole web
application instead of any particular servlet or JSP. It is a recommended practice for every Java
web application to have a default error page in addition to page specific error pages. This error page is
defined in configuration file web.xml by using tag <error-page>. <error-page> tag allows you to
define custom error page based upon HTTP error code or any Java Exception. You can define a default
error page for all exception by specifying <exception-type> as java.lang.Throwable and it would be
applicable to all exception thrown form any Servlet or JSP pages in your web application. Here is an
example of declaring default error page in Java web application based on HTTP Error code and Java
Exception type.
Default Error page based on Exception type:
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.htm</location>
</error-page>

Default Error page based on HTTP Error code:


<error-page>
<error-code>500</error-code>
<location>/internal-server-error.htm</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/page-not-found-error.htm</location>
</error-page>

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.

3.3 Including Files

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).

Figure 3.1: Including a file at compile-time vs. runtime

Including Files at Compile-Time


If you want to include a file at compile-time, then you need to use the JSP include directive. This method
of including files is generally more efficient and should be used whenever the included file is relatively
static and does not change much. Here's what the include directive looks like:
<%@ include file="myFile.html" %>

Including Files at Runtime


Sometimes, you may want to include some content that may change more frequently than a static page
header. One problem with using the include directive to include frequently changing files is that some
servlet engines will fail to recognize when an included file has been modified and will not recompile the
JSP. The solution to this problem is to include the file at runtime instead. Here's an example of including
a file at runtime:
<jsp:include page="myContent.jsp" flush="true"/>
The flush attribute tells the servlet engine to flush the output buffer before including the file. Another
benefit of including files in this manner is that you can pass parameters to the included page. Here's an
example of including a file with parameters:
<jsp:include page="conversion.jsp" flush="true">
<jsp:param name="temperature" value="76"/>
<jsp:param name="scale" value="celsius"/>
</jsp:include>
This will call the conversion.jsp file with the temperature and scale parameters. The output from this page
will be inserted in the output from the original JSP page. The only real restriction on including files in this
manner is that the included file can't change any of the HTTP headers. This makes sense because the
included file is really treated as a separate HTTP request and response, with only the output being inserted
into the original JSP.

3.4 Page Navigation

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.

3.5 Basic Form Processing

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.

Figure 3.3: Two-Page Form Handling Approach

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.

Figure 3.4: One-Page Form Handling Approach

Example 3-4: Basic form processing using two-page approach


File Name: simpleForm.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head><title>Simple Form</title></head>
<body>
<form method="post" action="formHandler.jsp">
<p>Name: <input type="text" name="username" size="20"></p>
<p>Languages known :<br>
English <input type="checkbox" name="language" value="English">
Hindi <input type="checkbox" name="language" value="Hindi">
Odiya <input type="checkbox" name="language" value="Odiya">
</p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>

File Name: formHandler.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Simple Processing</title>
</head>
<body>
<%
String username = request.getParameter("username");
String[] language = request.getParameterValues("language");

// form a string of known languages


String knownlang = "";
if (language != null) {
for (int i = 0; i < language.length; i++) {
knownlang = language[i]+ ", " +knownlang;
}
}
out.println("<h3>Your Name:"+ username+"</h3>");
out.println("<h3>You know: "+knownlang+ " languages.</h3>");
%>
</body>
</html>

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.

Example 3-5: Basic form processing using one-page approach


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Simple Form Handler</title>
</head>
<body>
<form method="post" action="process.jsp">
<p>Name: <input type="text" name="username" size="20"></p>
<p>Languages known :<br>
English <input type="checkbox" name="language" value="English">
Hindi <input type="checkbox" name="language" value="Hindi">
Odiya <input type="checkbox" name="language" value="Odiya">
</p>
<p><input type="submit" value="Submit"></p>
</form>
<%
if (request.getMethod().equals("POST")) {
String username = request.getParameter("username");
String[] language = request.getParameterValues("language");

// form a string of known languages


String knownlang = "";
if (language != null) {
for (int i = 0; i < language.length; i++) {
knownlang = language[i] + ", " + knownlang;
}
}
out.println("<h3>Your Name:" + username + "</h3>");
out.println("<h3> You know: " + knownlang + " languages.</h3>");
}
%>
</body>
</html>

3.6 Accessing Database


Java language provides JDBC API that allows you to store, retrieve, and manipulate data in virtually any
data source. To use JDBC API in a JSP page you need to have a page directive to import the necessary
JDBC classes as shown below:
<%@page import="java.sql.*"%>

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.

Example of Database Access using JSP

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.

Example 3-6: Simple Database Access in JSP


File Name: regForm.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<%
if(request.getParameter("msg")!= null)
out.println("<h3
style='color:red;'>"+request.getParameter("msg")+" </h3>");
%>
<h3>User Registration!</h3>
<form action="register.jsp" method="post">
User ID: <input type="text" name="uid"><br><br>
Password: <input type="password" name="pwd"><br><br>
Name: <input type="text" name="uname"><br><br>
Email: <input type="text" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
File Name: register.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<title>Example of Java Server Page with JDBC</title>
</head>
<body>
<% String userid=request.getParameter("uid");
String password=request.getParameter("pwd");
String name=request.getParameter("uname");
String email=request.getParameter("email");
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:myDB","","");

/* Passing argument through the parameterized statement */


PreparedStatement ps=con.prepareStatement("insert into login
values(?,?,?,?)");
ps.setString(1,userid);
ps.setString(2,password);
ps.setString(3,name);
ps.setString(4,email);
int i=ps.executeUpdate(); /* execute the insert query */
if(i!=0) {
response.sendRedirect("login.jsp?msg=Thank You for
registering!");
} else {
response.sendRedirect("regForm.jsp?msg=Insertion Failed!
Please try again! ");
}
con.close();
} catch(Exception ex) { out.println(ex); }
%>
</body>
</html>

File Name: login.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<%=request.getParameter("msg")%>
</body>
</html>
Lab Exercises:
Chapter-4

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.

4.1 Overview of Java Beans


JavaBeans components are Java classes that can be easily reused and composed together into applications.
Java Server Pages technology directly supports using JavaBeans components with standard JSP language
elements. You can easily create and initialize beans and get and set the values of their properties. A Java
Bean is simple Java class with a set of properties and satisfies the following design conventions:
It implements the Serializable interface so that it can be serialized by its container
It has a zero-argument constructor
It has set of accessor methods for each property to support customization of its state.
It may also include a set of custom methods to perform operations on the data it contains.
The Java Bean may have Simple property, Boolean property and Indexed property. The bean must
confirm the following conventions to expose these properties.

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) { }

An example of this type of property can be as follows:


private String studentName;

public void setStudentName(String newValue) {


studentNameString = newValue;
}

public String getStudentName() {


return studentName;
}
Boolean Property
For reading and writing the boolean property, the bean must have a pair of methods of the following
form:
public boolean isPropertyName() { }
public void setPropertyName(boolean value) { }

An example of this type of property can be as follows:


private boolean connected;

public void setConnected( boolean newValue) {


connected = newValue;
}

public boolean isConnected() {


return connected;
}

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);

An example of this type of property can be as follows:


private int[] numbers = {1, 2, 3, 4};

// set and get method for the complete array


public void setNumbers(int[] newValue) {
numbers = newValue;
}

public int[] getNumbers() {


return numbers;
}
// set and get method with index to set one element of array

public void setNumbers(int index, int newValue) {


numbers[index] = newValue;
}

public int getNumbers(int index) {


return numbers[index];
}
Let us consider an example of a JavaBean component called SimpleBean in Example 4-1.

Example 4-1: SimpleBean.java


package jspbook.ch4;

public class SimpleBean implements java.io.Serializable{


private String firstName;
private String lastName;

public SimpleBean() {
}

public String getFirstName() {


return firstName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getLastName() {


return lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

@Override
public String toString() {
return ("Hello "+firstName +
" " + lastName +
", <br>Welcome to the wonderful world of JavaBeans!");
}
}

4.2 Using JavaBeans in JSP


You can access a JavaBean within a JSP page either through a scriptlet or by using a special set of JSP
tags. Either way, before using a JavaBean you must first declare it and initialize it for use. You do this
through the <jsp:usebean> tag. This tag has two forms. Here's how this tag might look for our simple
bean:
Syntax:
<jsp:useBean id="beanName"
class="fully-qualified-classname" scope="bean-scope"/>
And

<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.

Accessing Bean Properties


You can set and retrieve the properties of a JavaBean using the <jsp:setProperty> and <jsp:getProperty>
tags, respectively. This will only work if your JavaBean has a set of accessor methods (getXxx and
setXxx) for each property. To set a property you could do it by different way (as shown in Table 4.1).
You'll use the simpleBean as an example.
Table 4.1: Different ways to set Bean property
Value Source Element Syntax Example
<jsp:setProperty
<jsp:setProperty name="beanName"
name="simpleBean"
String constant property="propName"
property="firstName"
value="string-constant"/>
value="Ananta"/>
<jsp:setProperty
Request parameter <jsp:setProperty name="beanName"
name="simpleBean"
does not match bean property="propName"
property="firstName"
property param="paramName"/>
param="fname"/>
<jsp:setProperty
<jsp:setProperty name="beanName" name="simpleBean"
Request parameter property="propName"/> property="firstName"/>
name that matches OR OR
bean property <jsp:setProperty name="beanName" <jsp:setProperty
property="*"/> name="simpleBean"
property="*"/>
<jsp:setProperty
<jsp:setProperty name="beanName"
name="simpleBean"
Expression property="propName"
property="firstName"
value="expression"/>
value="<%=fname%>"/>

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>

<!-- Display welcome message -->


<center>
<b><%= simpleBean.toString() %></b>
</center>

</body>
</html>

4.3 Form Processing using JavaBeans

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

<jsp:useBean id="userBean" class="bean.UserBean" scope="request">


<jsp:setProperty name="userBean" property="*"/>
</jsp:useBean>

<%
if (userBean.validate()) {
userBean.connectDB();
int r= userBean.saveUser();
if(r>0){
%>
<jsp:forward page="success.jsp"/>
<%
}
} else {
%>
<jsp:forward page="retry.jsp"/>
<%
}
%>

Example 4-5: UserBean.java


package bean;

import java.io.Serializable;
import java.util.HashMap;
import java.sql.*;

public class UserBean implements Serializable {


private String userid;
private String password;
private String username;
private String email;
private HashMap errors;
private Connection con;

public UserBean() {
userid="";
password="";
username="";
email="";
errors = new HashMap();
}

public String getUserid() {


return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}

public String getPassword() {


return password;
}

public void setPassword(String password) {


this.password = password;
}

public String getUsername() {


return username;
}

public void setUsername(String username) {


this.username = username;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public boolean validate() {


boolean allOK = true;
if (userid.equals("")) {
errors.put("userid", "User ID cannot be empty!");
allOK = false;
}
if (password.equals("")) {
errors.put("password", "Password cannot be empty!");
allOK = false;
}
if (username.equals("")) {
errors.put("username", "User Name cannot be empty!");
allOK = false;
}
if (email.equals("") || email.indexOf('@') == -1) {
errors.put("email", "Enter correct Email");
allOK = false;
}
return allOK;
}

public String getErrorMsg(String key) {


String errorMsg = (String) errors.get(key);
return (errorMsg == null) ? "" : errorMsg;
}

public void connectDB() {


try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
String dbURL = "jdbc:derby://localhost:1527/ojhadata";
con = DriverManager.getConnection(dbURL, "nbuser",
"nbuser");
} catch (Exception e) { }
}

public int saveUser() {


int r = 0;
try {
Statement st = con.createStatement();
String sql = "insert into APP.USERS values('" + userid +
"','" + password + "','" + username + "','" + email + "')";
r = st.executeUpdate(sql);
} catch (Exception e) { }
return r;
}
}

Example 4-6: success.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>JSP Page</title>
</head>
<jsp:useBean id="userBean" class="bean.UserBean" scope="request"/>
<body>
<h3>Congratulation!!</h3>
User Id: <jsp:getProperty name="userBean"
property="userid"/><br><br>
Password: <jsp:getProperty name="userBean"
property="password"/><br><br>
Name: <jsp:getProperty name="userBean"
property="username"/><br><br>
Email: <jsp:getProperty name="userBean"
property="email"/><br><br>
</body>
</html>
Example 4-7: retry.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head><title>User Registration Page</title></head>
<body>
<jsp:useBean id="userBean" class="bean.UserBean" scope="request"/>
<h3>User Registration</h3>
<form action="process.jsp" method="post">
<font color='red'>
<%=userBean.getErrorMsg("userid")%></font><br>
User ID: <input type="text" name="userid"
value='<%=userBean.getUserid()%>'><br><br>
<font color='red'>
<%=userBean.getErrorMsg("password")%></font><br>
Password: <input type="password" name="password"
value='<%=userBean.getPassword()%>'><br><br>
<font color='red'>
<%=userBean.getErrorMsg("username")%></font><br>
Name: <input type="text" name="username"
value='<%=userBean.getUsername()%>'><br><br>
<font color='red'>
<%=userBean.getErrorMsg("email")%></font><br>
Email: <input type="text" name="email"
value='<%=userBean.getEmail()%>'><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Figure 4.1: Form Processing Using JavaBeans


Lab Exercises:
Chapter-5

JSP Application Models


Objective: This chapter introduces JSP Application Models and how-to
implement Model 2 in order to leverage benefits of server-side Java
Technologies. After completing the chapter, you will learn to develop
better designed web applications for enterprises.

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.

Figure 5.1: JSP Model 1 Architecture

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.

Figure 5.2: JSP Model 2 Architecture

5.2 Using Model 2


To demonstrate the JSP Model 2 architecture, let us consider the user registration process we considered
previously to implement JavaBeans with JSP in last chapter. Actually that example implements JSP
Model 1 architecture. In that example, user submits an HTML form providing registration parameters.
The application uses a JavaBean to validate the data submitted. If the validation succeeds, the application
enters the data into the database using the bean and displays a registration success message to the user. In
case the validation fails, the application redisplays the HTML form with error messages and the data
previously filled by the user. This process ensures the user to enter correct data into the database.

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.

Figure 5.3: Refined Model 2 Architecture

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.

Example 5-1: 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="RegisterServlet" 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>

Example 5-2: RegisterServlet.java

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;

public class RegisterServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
// instatiate the bean component
UserBean userBean= new UserBean();

// populate the bean instance with form data

userBean.setUserid(request.getParameter("userid"));
userBean.setPassword(request.getParameter("password"));
userBean.setUsername(request.getParameter("username"));
userBean.setEmail(request.getParameter("email"));

/* put the bean instance in the request object,


* so that it will be available to other parts
*/
request.setAttribute("userBean", userBean);

// decide which JSP page to return to the user

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);
}
}

Example 5-3: UserBean.java

package bean;

import java.io.Serializable;
import java.util.HashMap;
import java.sql.*;

public class UserBean implements Serializable {

private String userid;


private String password;
private String username;
private String email;
private HashMap errors;
private Connection con;

public UserBean() {
userid="";
password="";
username="";
email="";
errors = new HashMap();
}

public String getUserid() {


return userid;
}

public void setUserid(String userid) {


this.userid = userid;
}

public String getPassword() {


return password;
}

public void setPassword(String password) {


this.password = password;
}

public String getUsername() {


return username;
}

public void setUsername(String username) {


this.username = username;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}

public boolean validate() {


boolean allOK = true;
if (userid.equals("")) {
errors.put("userid", "User ID cannot be empty!");
allOK = false;
}
if (password.equals("")) {
errors.put("password", "Password cannot be empty!");
allOK = false;
}
if (username.equals("")) {
errors.put("username", "User Name cannot be empty!");
allOK = false;
}
if (email.equals("") || email.indexOf('@') == -1) {
errors.put("email", "Enter correct Email");
allOK = false;
}
return allOK;
}

public String getErrorMsg(String key) {


String errorMsg = (String) errors.get(key);
return (errorMsg == null) ? "" : errorMsg;
}

public void connectDB() {


try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
String dbURL = "jdbc:derby://localhost:1527/ojhadata";
con = DriverManager.getConnection(dbURL, "nbuser", "nbuser");
} catch (Exception e) { }
}

public int saveUser() {


int r = 0;
try {
Statement st = con.createStatement();
String sql = "insert into APP.USERS values('" + userid +
"','" + password + "','" + username + "','" + email + "')";
r = st.executeUpdate(sql);

} catch (Exception e) { }
return r;
}
}

Example 5-4: success.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<title>JSP Page</title>
</head>
<jsp:useBean id="userBean" class="bean.UserBean" scope="request"/>
<body>
<h3>Congratulation!!</h3>
User Id: <jsp:getProperty name="userBean"
property="userid"/><br><br>
Password: <jsp:getProperty name="userBean"
property="password"/><br><br>
Name: <jsp:getProperty name="userBean"
property="username"/><br><br>
Email: <jsp:getProperty name="userBean"
property="email"/><br><br>
</body>
</html>

Example 5-5: retry.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>


<!DOCTYPE html>
<html>
<head>
<title>User Registration Page</title>
</head>
<body>
<jsp:useBean id="userBean" class="bean.UserBean" scope="request"/>
<h3>User Registration</h3>
<form action="RegisterServlet" method="post">
<font color='red'>
<%=userBean.getErrorMsg("userid")%></font><br>
User ID: <input type="text" name="userid"
value='<%=userBean.getUserid()%>'><br><br>
<font color='red'>
<%=userBean.getErrorMsg("password")%></font><br>
Password: <input type="password" name="password"
value='<%=userBean.getPassword()%>'><br><br>
<font color='red'>
<%=userBean.getErrorMsg("username")%></font><br>
Name: <input type="text" name="username"
value='<%=userBean.getUsername()%>'><br><br>
<font color='red'>
<%=userBean.getErrorMsg("email")%></font><br>
Email: <input type="text" name="email"
value='<%=userBean.getEmail()%>'><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Lab Exercises:

Anda mungkin juga menyukai