You are on page 1of 148

Your First JSP Page 04/28/09 03:44:52

Article
Home> Articles > JSP > Fundamentals

JSP Tutorial

This is a JSP tutorial to help a developer understand what is meant by Java Server Pages. The reader will learn the main
concepts, setup a JSP environment on their computer and write a few JSP programs. Why not learn JSP development
using our JSP source code examples?

1/148
Your First JSP Page 04/28/09 03:44:52
Introduction to JSP

Introduction to JSP

JavaServer Pages (JSP) is a technology based on the Java language and enables the development of dynamic web sites.
JSP was developed by Sun Microsystems to allow server side development. JSP files are HTML files with special Tags
containing Java source code that provide the dynamic content.

The following shows the Typical Web server,different clients connecting via the Internet to a Web server. In this
example,the Web server is running on Unix and is the very popular Apache Web server

2/148
Your First JSP Page 04/28/09 03:44:52

First static web pages were displayed. Typically these were people?s first experience with making web pages so consisted
of My Home Page sites and company marketing information. Afterwards Perl and C were languages used on the web
server to provide dynamic content. Soon most languages including Visualbasic,Delphi,C and Java could be used to write
applications that provided dynamic content using data from text files or database requests. These were known as CGI
server side applications. ASP was developed by Microsoft to allow HTML developers to easily provide dynamic content
supported as standard by Microsoft?s free Web Server,Internet Information Server (IIS). JSP is the equivalent from Sun
Microsystems,a comparison of ASP and JSP will be presented in the following section.

The following diagram shows a web server that supports JSP files. Notice that the web server also is connected to a
database.

JSP source code runs on the web server in the JSP Servlet Engine. The JSP Servlet engine dynamically generates the
HTML and sends the HTML output to the client?s web browser.

3/148
Your First JSP Page 04/28/09 03:44:52

4/148
Your First JSP Page 04/28/09 03:44:52
Why use JSP?

Why use JSP?


JSP is easy to learn and allows developers to quickly produce web sites and applications in an open and standard way. JSP
is based on Java,an object-oriented language. JSP offers a robust platform for web development.

Main reasons to use JSP:

Multi platform
Component reuse by using Javabeans and EJB.
Advantages of Java.
You can take one JSP file and move it to another platform,web server or JSP Servlet engine.

This means you are never locked into one vendor or platform.

HTML and graphics displayed on the web browser are classed as the presentation layer. The Java code (JSP) on the server
is classed as the implementation.

By having a separation of presentation and implementation,web designers work only on the presentation and Java
developers concentrate on implementing the application.

5/148
Your First JSP Page 04/28/09 03:44:52

JSP compared to ASP,ASP.NET and Servlets

JSP compared to ASP

JSP and ASP are fairly similar in the functionality that they provide. JSP may have slightly higher learning curve. Both
allow embedded code in an HTML page,session variables and database access and manipulation. Whereas ASP is mostly
found on Microsoft platforms i.e. NT,JSP can operate on any platform that conforms to the J2EE specification. JSP allow
component reuse by using Javabeans and EJBs. ASP provides the use of COM / ActiveX controls.

JSP compared to ASP.NET


ASP.NET is based on the Microsoft .NET framework. The .NET framework allows applications to be developed using
different programming languages such as Visual Basic,C# and JavaScript. JSP and Java still has the advantage that it is
supported on many different platforms and the Java community has many years of experience in designing and developing
Enterprise quality scalable applications. This is not to say that ASP.NET is bad,actually it is quite an improvement over
the old ASP code.

JSP compared to Servlets


A Servlet is a Java class that provides special server side service. It is hard work to write HTML code in Servlets. In
Servlets you need to have lots of println statements to generate HTML. JSP pages are converted to Servlets so actually can
do the same thing as old Java Servlets.

6/148
Your First JSP Page 04/28/09 03:44:52
JSP architecture

JSP architecture
JSPs are built on top of SUN Microsystems' servlet technology. JSPs are essential an HTML page with special JSP tags
embedded. These JSP tags can contain Java code. The JSP file extension is .jsp rather than .htm or .html. The JSP engine
parses the .jsp and creates a Java servlet source file. It then compiles the source file into a class file,this is done the first
time and this why the JSP is probably slower the first time it is accessed. Any time after this the special compiled servlet
is executed and is therefore returns faster.

Steps required for a JSP request:

1. The user goes to a web site made using JSP. The user goes to a JSP page (ending with .jsp). The web browser
makes the request via the Internet.
2. The JSP request gets sent to the Web server.
3. The Web server recognises that the file required is special (.jsp),therefore passes the JSP file to the JSP Servlet
Engine.
4. If the JSP file has been called the first time,the JSP file is parsed,otherwise go to step 7.
5. The next step is to generate a special Servlet from the JSP file. All the HTML required is converted to println
statements.
6. The Servlet source code is compiled into a class.
7. The Servlet is instantiated,calling the init and service methods.
8. HTML from the Servlet output is sent via the Internet.
9. HTML results are displayed on the user's web browser.

7/148
Your First JSP Page 04/28/09 03:44:52

8/148
Your First JSP Page 04/28/09 03:44:52

Setting up the JSP environment

Before setting up the JSP environment,you must make sure you have the JDK.

Download the latest JDK (with or without IDE) from the following URL:

http://java.sun.com/javase/downloads/index.jsp

For Windows,the complete download is about 50 MB.

Run through the setup.

One of the main problems new Java developers have is setting the PATH and CLASSPATH.

For Windows 95/98/ME you edit the AUTOEXEC.BAT file with the new PATH and CLASSPATH

settings and reboot your machine.

For Windows 2000/XP you edit the environment variables.

(Control Panel -> System -> Environment Variables).

See below. Read the installation instructions properly as it may change with future releases. What you do is add the
location of java's bin folder to the Path variable and the classes you want in the CLASSPATH variable.

9/148
Your First JSP Page 04/28/09 03:44:52

Both of these changes are described in the Java installation instructions.

Download the JSP environment

You can download JSP environments from the web.


http://java.sun.com/products/jsp/index.jsp

The preferred option is to download the Tomcat (approximately 7 to 10MB depending on the extras chosen). Tomcat is a
free open source JSP and Servlet engine,developed by Apache. Instructions to download Tomcat are given below.

http://tomcat.apache.org/

For Tomcat setup

To download Tomcat (current version 5.),go to the following URL:


http://tomcat.apache.org/download-55.cgi

10/148
Your First JSP Page 04/28/09 03:44:52

Unzip the file into a directory and set an environment variable TOMCAT_HOME to your main Tomcat directory:

For example, set TOMCAT_HOME=c:tomcat

To start the server change to the tomcatbin directory and type:


startup

Open a web browser and in the address box type:


http://localhost:8080/ - this displays the example page.

Place any new JSP files in the webapps directory under your installed Tomcat directory.

For example,to run myfirst.jsp file,copy the file into the webapps/ROOT directory and then open a browser to the address:
http://localhost:8080/myfirst.jsp

This will show you the executed JSP file.

CONGRATULATIONS - YOUR JSP and SERVLET ENVIRONMENT IS NOW SETUP!

11/148
Your First JSP Page 04/28/09 03:44:52
Creating your first JSP page
Creating your first JSP page

<html>
<head>
<title>My first JSP page
</title>
</head>
<body>
<%@ page language=java %>
<% out.println(Hello World); %>
</body>
</html>

Type the code above into a text file. Name the file helloworld.jsp.

Place this in the correct directory on your JSP web server and call it via your browser.

12/148
Your First JSP Page 04/28/09 03:44:52
Using JSP tags

Using JSP tags


There are five main tags:

1. Declaration tag
2. Expression tag
3. Directive tag
4. Scriptlet tag
5. Action tag

13/148
Your First JSP Page 04/28/09 03:44:52

Declaration tag
Declaration tag ( <%! %> )

This tag allows the developer to declare variables or methods.

Before the declaration you must have <%!

At the end of the declaration,the developer must have %>

Code placed in this tag must end in a semicolon ( ; ).

Declarations do not generate output so are used with JSP expressions or scriptlets.

For Example,

<%!
private int counter = 0 ;
private String get Account ( int accountNo) ;
%>

14/148
Your First JSP Page 04/28/09 03:44:52

Expression tag

Expression tag ( <%= %>)

This tag allows the developer to embed any Java expression and is short for out.println().

A semicolon ( ; ) does not appear at the end of the code inside the tag.

For example,to show the current date and time.

Date : <%= new java.util.Date() %>

15/148
Your First JSP Page 04/28/09 03:44:52

Directive tag

Directive tag ( <%@ directive ... %> )


A JSP directive gives special information about the page to the JSP Engine. There are three main types of directives:
1) page - processing information for this page.
2) Include - files to be included.
3) Tag library - tag library to be used in this page.

Directives do not produce any visible output when the page is requested but change the way the JSP Engine processes the
page.

For example,you can make session data unavailable to a page by setting a page directive (session) to false.

1. Page directive

This directive has 11 optional attributes that provide the JSP Engine with
special processing information. The following table lists the 11 different
attributes with a brief description:
language Which language the file uses. <%@ page language =
java %>
extends Superclass used by the JSP <%@ page extends =
engine for the translated com.taglib... %>
Servlet.
import Import all the classes in a java <%@ page import =
package into the current JSP java.util.* %>
page. This allows the JSP
page to use other java classes.
session Does the page make use of Default is set to true.
sessions. By default all JSP
pages have session data
available. There are
performance benefits to
switching session to false.
buffer Controls the use of buffered <%@ page buffer =
output for a JSP page. Default none %>
is 8kb
autoFlush Flush output buffer when full. <%@ page autoFlush =
true %>
isThreadSafe Can the generated Servlet deal
with multiple requests? If true
a new thread is started so

16/148
Your First JSP Page 04/28/09 03:44:52

requests are handled


simultaneously.
info Developer uses info attribute <%@ page info =
to add information/document visualbuilder.com test
for a page. Typically used to page,copyright 2001.
add author,version,copyright %>
and date info.
errorPage Different page to deal with <%@ page errorPage =
errors. Must be URL to error /error/error.jsp %>
page.
IsErrorPage This flag is set to true to make
a JSP page a special Error
Page. This page has access to
the implicit object exception
(see later).
contentType Set the mime type and
character set of the JSP.

2. Include directive

Allows a JSP developer to include contents of a file inside another. Typically


include files are used for navigation,tables,headers and footers that are
common to multiple pages.
Two examples of using include files: This includes the html
from privacy.html found in the include directory
into the current jsp page. <%@ include file =
include/privacy.html %> or to include a naviagation menu (jsp file) found in
the current directory. <%@ include file = navigation.jsp %> Include files
are discussed in more detail in the later sections of this tutorial. 3. Tag
Lib directive A tag lib is a collection of custom tags that can be used by the
page. <%@ taglib uri = tag library URI prefix = tag Prefix %> Custom tags
were introduced in JSP 1.1 and allow JSP developers to hide complex server
side code from web designers.

17/148
Your First JSP Page 04/28/09 03:44:52

Scriptlet tag

Scriptlet tag ( <% ... %> )


Between <% and %> tags,any valid Java code is called a Scriptlet. This code can access any variable or bean declared.

For example,to print a variable.

<%
String username = visualbuilder ;
out.println ( username ) ;
%>

18/148
Your First JSP Page 04/28/09 03:44:52

Action tag
Action tag

There are three main roles of action tags :

1) enable the use of server side Javabeans


2) transfer control between pages
3) browser independent support for applets.

Javabeans

A Javabean is a special type of class that has a number of methods. The JSP page can call these methods so can leave
most of the code in these Javabeans. For example,if you wanted to make a feedback form that automatically sent out an
email. By having a JSP page with a form,when the visitor presses the submit button this sends the details to a Javabean
that sends out the email. This way there would be no code in the JSP page dealing with sending emails (JavaMail API)
and your Javabean could be used in another page (promoting reuse).

To use a Javabean in a JSP page use the following syntax: Action tag

There are three main roles of action tags :

1) enable the use of server side Javabeans


2) transfer control between pages
3) browser independent support for applets.

Javabeans

A Javabean is a special type of class that has a number of methods. The JSP page can call these methods so can leave
most of the code in these Javabeans. For example,if you wanted to make a feedback form that automatically sent out an
email. By having a JSP page with a form,when the visitor presses the submit button this sends the details to a Javabean
that sends out the email. This way there would be no code in the JSP page dealing with sending emails (JavaMail API)
and your Javabean could be used in another page (promoting reuse).

To use a Javabean in a JSP page use the following syntax:

<jsp : usebean id = .... scope = application class = com... />

The following is a list of Javabean scopes:

page - valid until page completes.


request - bean instance lasts for the client request
session - bean lasts for the client session.
application - bean instance created and lasts until application ends.

19/148
Your First JSP Page 04/28/09 03:44:52

20/148
Your First JSP Page 04/28/09 03:44:52

Creating your second JSP page

Creating your second JSP page


For the second example,we will make use of the different tags we have learnt. This example will declare two variables;
one string used to stored the name of a website and an integer called counter that displays the number of times the page
has been accessed. There is also a private method declared to increment the counter. The website name and counter value
are displayed.

<HTML>
<HEAD>
<!-- Example2 -->
<TITLE> JSP loop</TITLE>
</HEAD>
<BODY>
<font face=verdana color=darkblue>
JSP loop
<BR> <BR>
<%!
public String writeThis(int x)
{
String myText=;
for (int i = 1; i < x; i++ )
myText = myText + <font size= i color=darkred face=verdana>VisualBuilder JSP Tutorial</font><br> ;
return myText;
}
%>

This is a loop example from the

<br>
<%= writeThis(8) %>
</font>
</BODY>
</HTML>

21/148
Your First JSP Page 04/28/09 03:44:52

Implicit Objects

Implicit Objects

So far we know that the developer can create Javabeans and interact with Java objects. There are several objects that are
automatically available in JSP called implicit objects.

The implicit objects are

Variable Of type
Request Javax.servlet.http.httpservletrequest
Response Javax.servlet.http. httpservletresponse
Out Javax.servlet.jsp.JspWriter
Session Javax.servlet.http.httpsession
PageContent Javax.servlet.jsp.pagecontext
Application Javax.servlet.http.ServletContext
Config Javax.servlet.http.ServletConfig
Page Java.lang.Object

Page object

Represents the JSP page and is used to call any methods defined by the servlet class.

Config object

Stores the Servlet configuration data.

Request object

Access to information associated with a request. This object is normally used in looking up parameter values and cookies.

<% String devStr = request.getParameter(dev); %>


Development language = <%= devStr %>
This code snippet is storing the parameter dev in the string devStr. The result is displayed underneath.

22/148
Your First JSP Page 04/28/09 03:44:52
Creating a Form

Creating a Form
Here we show how to create and process an html form.
Copy the code below and place in a file named: myform.jsp
Go to myform.jsp in your browser
You will see the form you just created.
It won't do anything yet.

<html>
<head>
<!-- Example4 -->
<title>VisualBuilder.com</title>
</head>
<body>
<form action=myformconfirm.jsp method=post>
Enter in a website name:<br>
<input type=text name=website><br>
<input type=submit name=submit>
</form>
</body>
</html>

23/148
Your First JSP Page 04/28/09 03:44:52
Processing a Form

Processing a Form
Here we show how to process the html form your just created.
Copy the code below and place in a file named: myformconfirm.jsp
Go to myform.jsp
Fill in some details and submit the form
You should see the results of your submission
<html>
<head>
<!-- Example4 -->
<title>VisualBuilder.com</title>
</head>
<body>
<font size=3>
Your info has been received:
<br><br>
<%
String sName = request.getParameter(website);
out.print(sName);
%>
</font>
</body>
</html>

24/148
Your First JSP Page 04/28/09 03:44:52

Creating a Form (more elements)

Creating a Form (more elements)


This example shows how to create and process more form elements.
Copy the code below and place in a file named: fullform.jsp

<html>
<head>
<!-- Example5 -->
<title>VisualBuilder.com</title>
</head>
<body>
<h1>
Website submission form
</h1>
<form action=fullformconfirm.jsp method=post>
Enter in the website name:
<input type=text name=website>
<br>
<br>
Enter in the url:
<input type=text name=url>
<br>
<br>
category:
<select name=category size=1>
<option selected value=java>java</option>
<option value=ejb>ejb</option>
<option value=servlet>servlet</option>
<option value=jsp>jsp</option>
<option value=jdbc>jdbc</option>
</select>
<br>
<br>
Description:
<textarea rows=4 cols='42' name=desc></textarea>
<br>
<br>
Search engines:
<input type=checkbox name=yahoo value=T>Yahoo
<input type=checkbox name=google value=T CHECKED>Google
<input type=checkbox name=altavista value=T>Altavista
<br>
<br>
<input type=submit name=submit value=Go>
</form>
</body>

25/148
Your First JSP Page 04/28/09 03:44:52

</html>

26/148
Your First JSP Page 04/28/09 03:44:52

Processing a Form (more elements)

Processing a Form (more elements)


Here we show how to process the html form your just created.
Copy the code below and place in a file named: fullformconfirm.jsp
Go to fullform.jsp
Fill in some details and submit the form
You should see the results of your submission

<html>

<head>
<!-- Example4 -->
<title>VisualBuilder.com</title>

</head>
<body>

<font size=3>
Thank you for your submission,it has been successfully received:
<br><br>
<%
String sName = request.getParameter(website);
String sUrl = request.getParameter(url);
String sCategory = request.getParameter(category);
String sDesc = request.getParameter(desc);
String sGoogle = request.getParameter(google);
String sYahoo = request.getParameter(yahoo);
String sAltavista = request.getParameter(altavista);
%>

Name:<%=sName%><br>
Url:<%=sUrl%><br>
Desc:<%=sDesc%><br>
Category:<%=sCategory%><br>
Desc:<%=sDesc%><br>
Google:<%=sGoogle%><br>
Yahoo:<%=sYahoo%><br>
Altavista:<%=sAltavista%><br>

</font>

</body>
</html>

27/148
Your First JSP Page 04/28/09 03:44:52

Processing a Form (more elements-2)

Processing a Form (more elements)

Here we show how to process the html form your just created.
Copy the code below and place in a file named: fullformconfirm.jsp
Go to fullform.jsp
Fill in some details and submit the form
You should see the results of your submission

<html>

<head>
<!-- Example4 -->
<title>VisualBuilder.com</title>

</head>
<body>

<font size=3>
Thank you for your submission,it has been successfully received:
<br><br>
<%
String sName = request.getParameter(website);
String sUrl = request.getParameter(url);
String sCategory = request.getParameter(category);
String sDesc = request.getParameter(desc);
String sGoogle = request.getParameter(google);
String sYahoo = request.getParameter(yahoo);
String sAltavista = request.getParameter(altavista);
%>

Name:<%=sName%><br>
Url:<%=sUrl%><br>
Desc:<%=sDesc%><br>
Category:<%=sCategory%><br>
Desc:<%=sDesc%><br>
Google:<%=sGoogle%><br>
Yahoo:<%=sYahoo%><br>
Altavista:<%=sAltavista%><br>

</font>

</body>
</html>

28/148
Your First JSP Page 04/28/09 03:44:52

29/148
Your First JSP Page 04/28/09 03:44:52

Getting Client Info

Getting Client Info


You can get information about a clients computer
Copy the code below and place in a file named: clientinfo.jsp
Run it from your browser -clientinfo.jsp

You should see the results of your submission

<html>

<head>
<!-- Example5 -->
<title>VisualBuilder.com</title>

</head>
<body>
Client computer details:
<br><br>
<b>Ip address</b>:
<br>
<%=request.getRemoteAddr()%>
<br><br>
<b>Computer name</b>:
<br>
<%=request.getRemoteHost()%>
<br><br>
</body>
</html>

30/148
Your First JSP Page 04/28/09 03:44:52

Review and next steps

What you have learnt so far


Now that you have learnt how to create some simple JSP code and grasped the fundamentals of JSP programming, you
can build on your knowledge and become an expert.

The following pages will cover the following topics

• Security
• Exception Handling
• Database access and use
• Design best practice
• Lots of ready to use examples and source code snippets

31/148
Your First JSP Page 04/28/09 03:44:52

Beans scopes in JSP

JavaBeans are reusable components. It represents a simple Java class with some properties. The bean properties are
accessed by Getter and Setter method. They are used to separate Business logic from the Presentation logic. Internally, a
bean is just an instance of a class. The JSP specification provides three basic tags for working with Beans :-

rn

jsp:useBean id=bean name class=bean class scope = page | request | session |application />

rn

rn
• <jsp:setProperty name = bean name property = someProperty value = someValue />

rn
• <jsp:getProperty name = bean name property = someProperty />

rn rn

Where bean name = the name that refers to the bean.


Bean class = name of the java class that defines the bean.
property = name of the property to be passed to the bean.
value = value of that particular property.

rn

The following is the explanation for the different scopes of a bean object in jsp:

rn

rn
1. Page scope:- This scope helps to keep the data available while the page is loading. Any object whose scope is
defined as page scope will disappear as soon as the response is sent to the browser. The object with a page scope
may be modified as often as desired within the particular page but the changes are lost as soon as the user moves
away from the page. By default all beans have page scope.

rn
2. Request scope:- Any object created in the request scope will be available as long as the request object is valid.
For example if the JSP page uses a <jsp:forward> tag, then the bean will be accessed in the forwarded page and if
redirect is used then the bean is destroyed.

rn
3. The Session scope:- In JSP terms, the data associated with the user has session scope. A session does not
correspond directly to the user; rather, it corresponds with a particular period of time the user spends at a site.
Typically, this period is defined as all the hits a user makes to a website between starting and exiting his browser.

rn
4. Application Scope:- The bean associated with the application scope will be accessible to all the users and all the
pages in the application.

32/148
Your First JSP Page 04/28/09 03:44:52

33/148
Your First JSP Page 04/28/09 03:44:52

JSP Bean scope examples

The following example will demonstrate the various bean scopes for the JSP application. All the examples will use the
Counter bean which has only one property counter of type int .

(1) Page Scope

Note:- This is the default scope for the bean object. So in the following JSP example bean1 is accessed only in this page
and not anywhere else.

<HTML>
<BODY>
<H1>Using Beans and Page Scope</H1>
<jsp:useBean id=bean1 class=com.visualbuilder.Counter scope=page />
<%bean1.setCounter(bean1.getCounter() + 1);%>
The counter value is: <jsp:getProperty name=bean1 property=counter />
</BODY>
</HTML>

(1) Request Scope

index.jsp

<jsp:useBean id=counter scope=request class=com.visualbuilder.Counter />


<html>
<head>
<title>Request Bean Example</title>
</head>
<body>
<%
counter.setCounter(10);
%>
<jsp:forward page=request.jsp />
</body>
</html>

request.jsp

<jsp:useBean id=counter scope=request class=com.visualbuilder.Counter />

<html>
<body>
<H3>Request Bean Example</H3>
<center><b>The current count for the counter bean is: </b>
<%=counter.getCounter() %></center>
</body>
</html>

(3) Session Scope

34/148
Your First JSP Page 04/28/09 03:44:52
Example for Session Scope.

<HTML>
<BODY>
<jsp:useBean id=bean1 class=com.visualbuilder.Counter scope=session />
<%bean1.setCounter(bean1.getCounter() + 1);%>
The counter value is:
<jsp:getProperty name=bean1 property=counter />
</BODY>
</HTML>

(3) Application Scope

<jsp:useBean id=counter scope=application class=com.visualbuilder.Counter />

<html>
<body>
<center>
&nbsp;&nbsp;<b>The current count for the counter bean is: </b> <%=counter.getCounter() %>
</center>
</body>
</html>

35/148
Your First JSP Page 04/28/09 03:44:52

Uploading Application in JSP.

The request object is used to send the raw data in form of key/value pair to the server from the browser. What if, we want
to send the multipart data i.e. images, files and binary data to the server. The below example will demonstrate the multiple
type data send to the server.

<%@ page import=java.io.*%>


<%
String contentType = request.getContentType();
if ((contentType != null) && (contentType.indexOf(multipart/form-data) >= 0)) {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();

byte dataBytes[] = new byte[formDataLength];


int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
String saveFile = file.substring(file.indexOf(filename=) + 10);
saveFile = saveFile.substring(0, saveFile.indexOf(n));
saveFile = saveFile.substring(saveFile.lastIndexOf(\) + 1,saveFile.indexOf());
int lastIndex = contentType.lastIndexOf(=);
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf(filename=);
pos = file.indexOf(n, pos) + 1;
pos = file.indexOf(n, pos) + 1;
pos = file.indexOf(n, pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
String filepath=session.getServletContext().getRealPath(/)+saveFile;
FileOutputStream fileOut = new FileOutputStream(filepath);

fileOut.write(dataBytes, startPos, (endPos - startPos));


fileOut.flush();
fileOut.close();
out.println(File saved as +saveFile);
}
%>

<!-- Starts Here -->


<form method=post ACTION=upload.jsp name=uploadForm ENCTYPE='multipart/form-data'>
<input type=file name=uploadfile />
<p>
<input type=submit name=Submit value=Submit>
<input type=reset name=Reset value=Reset>
<input type=hidden name=action value=upload>

36/148
Your First JSP Page 04/28/09 03:44:52
</p>
</form>
<!-- Ends Here -->

Output:-

37/148
Your First JSP Page 04/28/09 03:44:52
Modularization in JSP

These days, users expect feature rich online applications and companies need flexible application design to deal with
complex business rules. The day of having a single code file with all the application are gone. Modularization is the
splitting up of complex code into separate modules of code. The following are the advantages of the modularization:-

1. Coding and debugging both are very easy as compared to single file.
2. The code is reused if required in the multiple pages.
3. If any logic becomes obsolete then it can be replaced without disturbing other components in the application. The
following tags are used to add the multiple JSP pages into one:-
a. <jsp:include>:- The <jsp:include> includes the given file on runtime. When container encounters this tag, it
checks for the JSP file and compile that given JSP file. The output is then included in the page at runtime. As a
result response time increases to some extent. It is always better to use <jsp:include> when the JSP page content
are dynamically changes and the restarts of the servers are not done periodically.
b. <%@include%>:- This tag includes the contents of the given file during the compilation of the JSP file. When
the container encounter this tag it will generate the servlet and include all the contents of the included file to the
servlet. Now if we change the included file then it would not reflect to its parent page until or unless it is reloaded
to the container or the server gets a restart. So it is always better to use <%@include%> for the static type of the
pages.

Example:-

The below is given the use of the <jsp:include> and also the <%@include%> tag.

<jsp:include page=coretaglib1.jsp/><br>
<%@include file=coretaglib2.jsp%>

Output

The below output will be displayed.

38/148
Your First JSP Page 04/28/09 03:44:52

Exception Handling in JSP-1

An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's
instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system.
The object, called an exception object, contains information about the error, including its type and the state of the program
when the error occurred. There are two ways to handle the exceptions in the JSP world. First- is the conventional
try/catch/finally block in the scriptlet. In this way you have to handle the flow of the program.

The following example will demonstrate the conventional way of error handling.

Example:-

<%
try{
String str=11a;
int i = Integer.parseInt(str);
}catch(Exception e){
out.println(Error Occured);
}
%>

Output:-

The above example will print the Error occurred as output. The page is throwing a NumberFormatException while
converting string to integer. As a result, the control is transferred to the catch block of the program.

39/148
Your First JSP Page 04/28/09 03:44:52

Exception Handling in JSP-2

The second way is to define the error page in the page directive as <%@ page errorPage=errorpage.jsp %> and creating
the error page. When any exception or error occurs while processing the JSP page then the container automatically calls
the error page and redirects the flow to it. Any page can be used to show the errors.Users have to set the ErrorPage=true
property on the page directive for example:-<%@ page isErrorPage=true %> for error pages. While processing an error
page an implicit object named exception automatically created for the page, which is used to display the error messages.

The below example will demonstrate the exception handling in the JSP and use of exception implicit object.

Exceptionhandling.jsp

<%@ page errorPage=errorpage.jsp %>


<%

String s=null;
s.toString();

%>

errorpage.jsp

<%@ page isErrorPage=true %>

This is the Error page.The following error occurs:- <br>


<%= exception.toString() %>

Output:-

40/148
Your First JSP Page 04/28/09 03:44:52
Session Tracking in JSP

In any web application, a user moves from one page to another. So, it is necessary to track the user's data and objects
throughout the application. As we know that the session keeps the data particular to a user, so sessions are used to hold the
user's data. For sessions JSP provide an implicit object session, which can be use to save the data specific to the particular
user into the session scope.

There are mainly 4 ways for session Tracking as follows:

1. Cookies:-
You can use HTTP cookies to store information about a session. The cookies are small text files stored in the client side.
This is an excellent most widely used approach. However, even though servlets have a high-level and easy-to-use
interface to cookies, there are still a number of relatively tedious details that need to be handled, while working with
cookies.

2. URL Rewriting:
You can append some extra data on the end of each URL that identifies the session, and the server can associate that
session identifier with data it has stored about that session. This is also an excellent solution, and even has the advantage
that it works with browsers that don't support cookies or where the user has disabled cookies. However, it has most of the
same problems as cookies, namely that the server-side program has a lot of straightforward but tedious processing to do.

3. Hidden form fields:


HTML forms have an entry that looks like the following: <INPUT TYPE=HIDDEN NAME=session VALUE=...>. This
means that, when the form is submitted, the specified name and value are included in the GET or POST data. This can be
used to store information about the session. However, it has the major disadvantage that it only works if every page is
dynamically generated, since the whole point is that each session has a unique identifier.

4. Using session object in the JSP.

The implicit object represents the session. The information can be stored in the session for the current session by
setAttribute() and then retrieve by getAttribute() method, whenever needed. The session objects stores at the server so it is
advisable not to put heavy information in the session object.

To understand a session let us take a very simple example of getting the name from the user and saving it in the session,
we will retrieve this name from session on next page and display on the page. For this, we will need 2 JSP pages.

Example:-

Sessiontracking1.jsp

<% String action= request.getParameter(action);


if(action != null && action.equals(sub mit)){
String username=request.getParameter( username);
String password=request.getParameter(password);
if(username != null && password != null && username.equals(visualbuilder) && pa ssword.equals(test))

41/148
Your First JSP Page 04/28/09 03:44:52
{
session.setAttribute(username,username);
response.sendRedirect(sessiontracking2.jsp);
}else{
out.println(<h3>Wrong password!!!!</h3>);
}
}else{
%>

<html>
<form action=sessiontracking1.jsp method=post>
<input type=hidden name=action value=submit>
Enter the user name :- <input type=text name=username ><br>
Enter the password :- <input type=password name=password ><br>
<input type=submit name=submit value=submit>
</form>
</html>
<%}%>

Sessiontracking2.jsp

<h3>Welcome <%= session.getAttribute(username)%> To the Site</h3>

Output:-

42/148
Your First JSP Page 04/28/09 03:44:52

Security in JSP -1

Security is defined as the condition of being protected against danger or loss. The security is very important in any web
application as the web applications are mostly exposed to all the people in the world. The levels of security can be

• Transport Level security using HTTPS.


• Authentication and Authorization
• Role Based Access Control
• Container-managed Security
• Application-managed Security.

The web application can be configured to use any level of security as per the requirement and criticality of the site.

Application Managed Vs Container Managed Security


Container Managed Application Managed

• Authentication and Authorization are specified in • Using the Username and Password forms..
web.xml. • Cookies
• It uses multiple authentication schemes, such as • Using Servlet Filters.
Password Authentication Form-based • Using SSLEXT with Struts to enable
Authentication Client side Digital Certificates etc.. HTTPS.
• Redirects are handled automatically.
• User data can be provided by a variety of stores xml
file or flat files. In tomcat the Data is provided in
TOMCAT_HOME/conf/tomcat-users.xml
The following is the Example to implement the Container Specific Security in Tomcat.

(1) tomcat-user.xml File

<?xml version =' 1.0 ' encoding =' utf-8 '?>


<tomcat-users>
<role rolename = tomcat />
<role rolename = role1 />
<role rolename = admin />
<user username = tomcat password = tomcat roles = tomcat />
<user username = both password = tomcat roles = tomcat,role1 />
<user username = role1 password = tomcat roles = role1 />
<user username = visualbuilder password = test roles = admin />
</tomcat-users>

(2) Web.xml file

<?xml version = 1.0 encoding = UTF-8 ?>


<web-app version = 2.4 xmlns = http://java.sun.com/xml/ns/j2ee xmlns:xsi =
http://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation = http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd >
<security-constraint>
<web-resource-collection>
<web-resource-name> application </web-resource-name>
<url-pattern> /security.jsp</url-pattern>

43/148
Your First JSP Page 04/28/09 03:44:52
</web-resource-collection>
<auth-constraint>
<role-name> admin </role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method> BASIC </auth-method>
<realm-name> securityapp </realm-name>
</login-config>
<security-role>
<description> Testing the Application Security </description>
<role-name> admin </role-name>
</security-role>
</web-app>

Output:-

The following screen appears when you try to run the application. It will ask for username and password and once you
enter visualbuilder as username and test as password then only it will display the pages of the application.

44/148
Your First JSP Page 04/28/09 03:44:52

Security in JSP -2

The user can also use the html forms to accept the username and password. This helps to establish the application level or
module level security in web world. All sites follow the different security policies and standards. It is always better to use
the application managed security for better results. Also, when the application is moved to some other servers then it
hardly impacts the application managed security. The following example will demonstrate a form and shows the welcome
message if user enters the correct username and password.

Example:-

<% String action= request.getParameter(action);


if(action != null && action.equals(submit)){
String username=request.getParameter(username);
String password=request.getParameter(password);
if(username != null && password != null && username.equals(visualbuilder) && password.equals(test))
{
out.println(<h3>welcome to the page</h3>);
}else{
out.println(<h3>Wrong password!!!!</h3>);
}
}else{
%>

<html>
<form action=formsecurity.jsp method=post>
<input type=hidden name=action value=submit>
Enter the user name :- <input type=text name=username ><br>
Enter the password :- <input type=password name=password ><br>
<input type=submit name=submit value=submit>
</form>
</html>
<%}%>

Output:-

45/148
Your First JSP Page 04/28/09 03:44:52

Internationalization in JSP application

Few years back, the sites were developed using a single language and the developer used to create the sites to their
specific languages. As the globalization occured, many frameworks have developed to support the multiple languages at a
time. Now this can be achieved by having the multi language text in key/value pair and at runtime the text is read from the
key as per the language required. This multilingual support is known as Internationalization. Internationalization is
defined as the process of designing an application so that it can be adapted to various languages and regions without
engineering changes.

The following classes are used to implement Internationalization to any site.

• Locale - The fundamental Java class that supports internationalization is Locale . Each Locale represents a
particular choice of country and language, and also a set of formatting assumptions for things like numbers and
dates.
• ResourceBundle - The java.util.ResourceBundle class provides the fundamental tools for supporting messages in
multiple languages.
• PropertyResourceBundle - One of the standard implementations of Resource Bundle allows you to define
resources using the same name=value syntax used to initialize properties files. This is very convenient for
preparing resource bundles with messages that are used in a web application, because these messages are
generally text oriented.

Note:- The fmt is the jstl tag library used to implement the internationalization in JSP. The below example will tell you
how to use the fmt taglib in the application. The example displays the text coming from the different properties files. The
properties file lables.properties is created with different locale suffix example en is for english, de for Germany etc. We
have hello key in both the files. hello=This is german File in de file and hello=This is english File in english file.

Example JSP file Internationalization.jsp file .

<%@ taglib prefix=fmt uri=/WEB-INF/fmt.tld%>


<fmt:setLocale value=de scope=session/>
<fmt:bundle basename=com.visualbuilder.labels>
<fmt:message>
hello
</fmt:message>
</fmt:bundle>

Output:-

The file will display This is german File and if the locale is changed to en then it will display the This is english file.

46/148
Your First JSP Page 04/28/09 03:44:52
Introduction To Expression Language.

A primary feature of JSP technology version 2.0 is its support for an expression language (EL). An expression language
makes it possible to easily access application data stored in JavaBeans components. As the EL is introduced in JSP 2.0,
we can also use the page attribute isELIgnored to ignore the EL for a page.

<%@ page isELIgnored =true|false %>

The following is the EL operator table which can be used with the EL language.

Note:- and,eq,gt,true,instanceof,or,ne,le,false,empty, not,lt,ge,null,div and mod are reserved words in the EL so user
cannot use these words for the identifiers.

Expression Result
${3+2-1} ${3+2-1} <%-- Addition/Subtraction --%>
${1+2} ${1+2} <%-- String conversion --%>
${1 + 2*3 + 3/4} ${1 + 2*3 + 3/4} <%-- Mult/Div --%>
${3%2} ${3%2} <%-- Modulo --%>
${(8 div 2) mod 3} ${(8 div 2) mod 3} <%-- Compares with equals but returns false for null --%>
${1<2} ${1<2} <%-- Numerical comparison --%>
${a<b} ${a<b} <%-- Lexical comparison --%>
${2/3 >= 3/2} ${2/3 >= 3/2} <%-- >= --%>
${3/4 == 0.75} ${3/4 == 0.75} <%-- Numeric = --%>
${null == test} ${null == test}
${(1<2) && (4<3)} ${(1<2) && (4<3)} <%--AND--%>
${(1<2) || (4<3)} ${(1<2) || (4<3)} <%--OR--%>
${!(1<2)} ${!(1<2)} <%-- NOT -%> <%-- Handles null or empty string in request param --%>
${empty } ${empty } <%-- Empty string --%>
${empty null} ${empty null} <%-- null --%>

47/148
Your First JSP Page 04/28/09 03:44:52

Introduction to Tag libraries

JSTL is a component technology within the Java 2 Enterprise Edition (J2EE) specification and is controlled by Sun
Microsystems. JSTL is nothing more than a set of simple and standard tag libraries that encapsulates the core functionality
commonly needed when writing dynamic JSP pages. The following are the problems with the JSPs:-

1. Java code embedded within scriptlet tags is ugly and obtrusive.


2. It is very difficult to modify the java code embedded in the JSP files if the file is large.
3. Java code within JSP scriptlets cannot be reused by other JSP pages.
4. Retrieving objects out of the HTTP request and session is cumbersome and type casting to the object's class is
required.

The JSTL tags are basically categorized into four libraries:

• core:- Basic scripting functions such as loops, conditionals, and input/output.


• fmt:- Internationalization and formatting of values such as currency and dates.
• xml:- XML processing
• sql:- Database access.

Advantages of using JSTL:-

• JSTL tags are XML based tags which are cleanly and uniformly blend into a page's HTML markup tags.
• The four JSTL tag libraries include most functionality that would be needed in a JSP page. JSTL tags are easier
for non-programmers and inexperienced programmers, because they do not require any knowledge of Java
programming.
• JSTL tags encapsulate reusable logic such as formatting dates and numbers.
• JSTL tags can reference objects in the request and session without knowing the object's type and no casting is
required.
• JSP's EL (Expression Language) makes it easy to call getter and setter methods on Java objects. This is not
possible in JSP 1.2, but became available in JSP 2.0. EL is used extensively in JSTL.

JSTL Drawbacks:

• JSTL can add processing overhead to the server. Both Java scriptlet code and tag libraries are compiled into a
resulting servlet, which is then executed by the servlet container. Java code embedded in scriptlet tags is directly
copied into the resulting servlet. But JSTL tags add more than required code to the servlet.
• Although JSTL provides a powerful set of reusable libraries, it cannot do everything that Java code can do. It is
designed to facilitate scripting the presentation code that is typically found in the view tier of
Model-View-Controller applications.

48/148
Your First JSP Page 04/28/09 03:44:52

Introduction To Core Taglib -1

Core taglib is the important taglib in the JSTL. It includes the core concepts of the programming like declaring the
variable, decision making tags etc.. The next sections will explain all the core taglib tags, which are generally used in the
programming.

Standard Syntax:
<%@ taglib prefix=c uri=http://java.sun.com/jsp/jstl/core %>

Variable Support Tags

The <c:set> tag sets the value of an EL variable or the property in any of the JSP scopes (page, request, session, or
application). If the variable does not exists, it will be created.

The JSP EL variable or property can be set either from the attribute value:

<c:set var=var scope=session value=.../>

OR

<c:set var=var>
...
</c:set>

To remove an EL variable, you use the <c:remove> tag as follows:

<c:remove var=test scope=session/>

Conditional Tags
The <c:if> tag allows the conditional execution of its body according to the value of the test attribute. The syntax of the
<c:if> conditional block is as follows:-

<c:if test=${condition}> </c:if>

The <c:choose> tag performs conditional block execution by the embedded <c:when> tags. It renders the body of the first
<c:when> tag whose test condition evaluates to be true. If none of the test conditions evaluates to be true, then the body of
<c:otherwise> tag is evaluated, if present. The syntax is as follows :-

<c:choose>
<c:when test=condition1 >
...
</c:when>
<c:when test=condition2 >
...
</c:when>
<c:otherwise>
</c:otherwise>
</c:choose>

49/148
Your First JSP Page 04/28/09 03:44:52
Introduction To Core Taglib -2

Iterator Tags

The <c:forEach> tag allows you to iterate over a collection of objects. You specify the collection via items attribute, and
the current item is available through a variable named given in the var attribute. A large number of collection types are
supported by <c:forEach>, including all implementations of java.util.Collection and java.util.Map. If given collection is
of type java.util.Map, then the current item will be of type java.util.Map.Entry, which has the following properties:

• key: The key under which the item is stored in the underlying Map
• value: The value that corresponds to the key

Arrays of objects as well as arrays of primitive types (for example, int) are also supported. For arrays of primitive types,
the current item for the iteration is automatically wrapped with its standard wrapper class (for example, Integer for int,
Float for float, and so on).

<c:forEach var=item items=collection>


</c:forEach>
or

<c:forEach begin=0 end=10 varStatus=status step=1 >

</c:forEach>

URL Tags

The <c:url> tag is used to create the URL for the submit actions or the hyperlinks. The <c:url> tag is used to create the
URL variable and <c:param> is used to add the parameters in the <c:url> tag. The syntax is as follows:-

<c:url var=var value=... >


<c:param name=param1 value=val1 />
</c:url>

Example:-

<%@ taglib uri=/WEB-INF/c.tld prefix=c %>


<%
String[] value = new String[10];
value[0]=one;
value[1]=two;
value[2]=three;
value[3]=four;
value[4]=five;

50/148
Your First JSP Page 04/28/09 03:44:52
value[5]=six;
value[6]=seven;
value[7]=eight;
value[8]=nine;
value[9]=ten;
pageContext.setAttribute(values,value);
%>
<b>Iterator For loop <br></b>
<c:forEach var=item varStatus=status items=${values}>
Place <c:out value=${status.index}/> value is <c:out value=${item}/><br>
</c:forEach>
<br>
<b>Coventional For Loop<br></b>
<c:forEach begin=0 end=10 varStatus=status step=1 >
Place <c:out value=${status.index}/> value is <c:out value=${values[status.index]}/><br>
</c:forEach>

<c:url var=yahoo value=http://www.yahoo.com/>

<a href=${yahoo}>yahoo url</a>

51/148
Your First JSP Page 04/28/09 03:44:52

52/148
Your First JSP Page 04/28/09 03:44:52

Function Taglib

The function taglib contains the basic String functions for the JSTL functionality.

Standard Syntax:

<%@ taglib prefix=fn uri=http://java.sun.com/jsp/jstl/functions %>

Return Type Method Description


contains ( java.lang.String,
boolean Tests if an input string contains the specified substring.
java.lang.String)
containsIgnoreCase ( Tests if an input string contains the specified substring in a case
boolean
java.lang.String, java.lang.String) insensitive way.
endsWith ( java.lang.String,
boolean Tests if an input string ends with the specified suffix.
java.lang.String)
java.lang.String escapeXml ( java.lang.String) Escapes characters that could be interpreted as XML markup.
indexOf ( java.lang.String, Returns the index withing a string of the first occurrence of a
int
java.lang.String) specified substring.
join ( java.lang.String[],
java.lang.String Joins all elements of an array into a string.
java.lang.String)
Returns the number of items in a collection, or the number of
int length ( java.lang.Object)
characters in a string.
replace ( java.lang.String, Returns a string resulting from replacing in an input string all
java.lang.String
java.lang.String, java.lang.String) occurrences of a before string into an after substring.
split ( java.lang.String,
java.lang.String[] Splits a string into an array of substrings.
java.lang.String)
startsWith ( java.lang.String,
boolean Tests if an input string starts with the specified prefix.
java.lang.String)
java.lang.String substring ( java.lang.String, int, int) Returns a subset of a string.
substringAfter ( java.lang.String,
java.lang.String Returns a subset of a string following a specific substring.
java.lang.String)
substringBefore ( java.lang.String,
java.lang.String Returns a subset of a string before a specific substring.
java.lang.String)
java.lang.String toLowerCase ( java.lang.String) Converts all of the characters of a string to lower case.
java.lang.String toUpperCase ( java.lang.String) Converts all of the characters of a string to upper case.
java.lang.String trim ( java.lang.String) Removes white spaces from both ends of a string.

Example:-

<%@ taglib uri=/WEB-INF/fn.tld prefix=fn %>


<%@ taglib uri=/WEB-INF/c.tld prefix=c %>
<c:set var=test value=This is the test String/>
Index of i is :- ${fn:indexOf(test, i)}<br>
Substring Function:- ${fn:substring(test, 3,10)}<br>
Upper Case :- ${fn:toUpperCase(test)}<br>
Lower Case:- ${fn:toLowerCase(test)}<br>
Replace Function:- ${fn:replace(test,the,a)}<br>

53/148
Your First JSP Page 04/28/09 03:44:52

contains Function:- ${fn:contains(test,the)}<br>

Output:-

54/148
Your First JSP Page 04/28/09 03:44:52
Database Handling in JSP.

The database interaction with the JSP page is similar to the core JDBC interaction. The complete JDBC code for the
database interaction is to be written in the scriptlet tags. The following example shows the process of database handling
with the JSP page. The following example will display the total hit for the current page and update the counter in the
database.

<%@page import=java.sql.* %>


<%
int hitCount=0;
try{
Class.forName(org.gjt.mm.mysql.Driver);
Connection connection = DriverManager.getConnection(jdbc:mysql://localhost:3306/test, root, root);
Statement statement = connection.createStatement();
int changed = statement.executeUpdate(update counters set hitCount = hitCount + 1 +where page like ' +
request.getRequestURI() + ');
if (changed == 0) statement.executeUpdate(insert counters(page) values(' + request.getRequestURI() + '));
ResultSet rs = statement.executeQuery(select hitCount from counters where page like ' + request.getRequestURI()
+ ');
rs.next();
hitCount = rs.getInt(1);
}catch(Exception e ){
}finally{
statement.close();
connection.close();
}
out.println(The hit count is +hitCount );
%>

Output:-

The page prints The hit count is 5 as output.

55/148
Your First JSP Page 04/28/09 03:44:52

Creating User Defined Custom Tag -1

The most powerful feature of JSP is that - the user can also create their own custom tags. The servlet API contains the
javax.servlet.jsp.tagext.BodyTagSupport class, which is used to create the custom tags. All the tags need to extend the
javax.servlet.jsp.tagext.BodyTagSupport class and override doStartTag(), doEndTag() and doAfterBody() methods. After
creating the Java class for the custom tag, the tag library description file is to be created. The extension for the XML
description file is .tld. The following example will create a tag, which takes String and prints the reverse of the String
when displayed on the browser.

ReverseTag.java

package com.visualbuilder.taglibrary;

import java.io.IOException;

import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class ReverseTag extends BodyTagSupport {

/**
*
*/
private static final long serialVersionUID = 1L;

public int doStartTag() throws JspTagException{


return EVAL_BODY_TAG;
}
public int doEndTag() throws JspTagException {
try {
JspWriter out = pageContext.getOut();
} catch (Exception ex) {
throw new JspTagException(All is not well in the world. + ex);
}
return SKIP_BODY;
}

public int doAfterBody() throws JspTagException {

BodyContent body = getBodyContent();


try {
// Make sure we put anything in the output stream in the
// body to the output stream of the JSP
JspWriter out = body.getEnclosingWriter();
String bodyContent = body.getString();
if (bodyContent != null) {
for (int i = bodyContent.length() - 1; i >= 0; i--) {

56/148
Your First JSP Page 04/28/09 03:44:52
out.print(bodyContent.charAt(i));
}
}
out.println();
body.clearBody(); // Clear for next evaluation
} catch (IOException ioe) {
throw new JspTagException(Error in reverse tag doAfterBody + ioe);
}
return (SKIP_BODY);

}
}

57/148
Your First JSP Page 04/28/09 03:44:52
Creating User Defined Custom Tag -2

The following is the tag lib descriptor file for the reverse tag.

<?xml version=1.0 encoding=ISO-8859-1 ?>


<!DOCTYPE taglib PUBLIC -//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN
http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd>
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>Visualbuilder</shortname>
<info>Visual builder Tag library</info>
<tag>
<name>stringreverse</name>
<tagclass>com.visualbuilder.taglibrary.ReverseTag </tagclass>
<info>
This is a simple tag which will reverse the text.
</info>
<!-- Optional attributes -->
</tag>
</taglib>

CustomTag.jsp file

<%@ taglib uri=/WEB-INF/reverse.tld prefix=reverse %>

<html>
<head>
<title>Your Custom Tag library</title>
</head>
<body bgcolor=#ffffff>
<hr />
<reverse:stringreverse>
Visual Builder
</reverse:stringreverse>
<hr />
</body>
</html>

Output:-

58/148
Your First JSP Page 04/28/09 03:44:52
Best Practices in JSP

There are some standard practices that can be followed while writing the JSP files. The standards of writing JSP code
helps to develop the application easily and effectively. It reduces the complexity and the debugging time for the JSP
application. The following are the best practices, while working on JSP application:-

• Separate HTML from Java:- For small JSP files with least of logic, it seems as best to have the Java and html in
the same JSP file as all available resources and dependencies are in the same file. As the JSP's go on to higher
complexity, this approach fails as the code becomes
complex and less readable and hard to understand.
• Place business logic in JavaBeans:- We must write our business logic in JavaBeans as the code will be reused
anywhere in the application. Also if any logical change occurs during the development so it requires to change
only at one place and hence avoiding rework everywhere.
• Factor general behavior out of custom tag handler classes:- If we are using custom tags then we must tend to
write the common code in a Java file separately instead of writing inside the customTagHandler. Because Handler
classes are not readily used like ordinary Java utility classes rather Handler classes can access the utility classes
easily.
• Favor HTML in Java handler classes over Java in JSPs:- Sometimes cleanly separating HTML, JSP tags, and
HTML-like custom tags from Java requires unnecessarily convoluted code. In these cases, you either include Java
scriptlets and expressions in the JSP or put some HTML code in the Java tag handler class.
• Use an appropriate inclusion mechanism: - The JSP is a combination of the tags and the Java code. It is very
difficult to maintain the two types of code in a single file. JSP gives us the flexibility to create the multiple JSP
pages and then call those JSP pages into the complex page wherever required.
• Use a JSP template mechanism:- Using templates is the best approach when we can see the total structural
changes in the look and feel of the page. It is not a good way to change each and every JSP page for the html
changes, rather we will define the layout of the page in a JSP and will use the templates mechanism to import the
contents of different portions from different JSP's through templates. So, when you want to change the layout, you
need to modify only one template file rather making changes in all pages.
• Use stylesheets:- We must use CSS to give the styles to different components across the site, providing same CSS
styles to similar kind of components. If we want to change the look of a particular type of component throughout
the website, we are required to change one style only and it will be reflected everywhere.

59/148
Your First JSP Page 04/28/09 03:44:52

JSP HTML Form source example

The previous section has explained what all controls are used in HTML for creating the forms. Lets see with the help of
below example how do we get the form data in JSP page which is send by the user.

We need to first define which JSP page should be accessed when this form is submitted. This can be achieved by the
action attribute in the <form>. For example:- <form action=/login.jsp> will generate a request for the login.jsp page
when the submit button will be clicked for the form.

We will be creating the input1.jsp file which will show the data which user has sent from login.html page from the
previous example.

Example:-

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN


http://www.w3.org/TR/html4/loose.dtd>
<html>

<head>
<meta http-equiv=Content-Language content=en-us>
<meta http-equiv=Content-Type content=text/html; charset=windows-1252>
<title>Login Form</title>
</head>

<body>

<p align=left><b>Login Form

</b></p>

<form method=POST action=login.jsp name=loginForm>

<table border=1 width=50% cellspacing=1 cellpadding=0 id=table1>


<tr>
<td width=50%>&nbsp;Login Name</td>
<td><input type=text name=loginName size=20></td>
</tr>
<tr>
<td width=50%>Password</td>
<td><input type=password name=password size=20></td>
</tr>
</table>
<p><input type=submit value=Submit name=B1><input type=reset value=Reset
name=B2></p>
</form>

</body>

</html>
JSP page:-

60/148
Your First JSP Page 04/28/09 03:44:52

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Login Form Data</title>
</head>
<body>
<b>Submitted Values are </b>
<table border=1 width=50% cellspacing=1 cellpadding=0 id=table1>
<tr>
<td width=50%>&nbsp;Login Name</td>
<td><%=request.getParameter(loginName) %></td>
</tr>
<tr>
<td width=50%>Password</td>
<td><%=request.getParameter(password) %></td>
</tr>
</table>
</body>
</html>
Output:- The following screen will be displayed when login form will gets submitted.

61/148
Your First JSP Page 04/28/09 03:44:52
Creating Web Application

Creating Web Application in Eclipse


The following are the steps which will create the web application using eclipse.

1. Goto File > new >project or right click the project explorer and then select new>project option.
2. Project dialog box appears.
3. Select the Dynamic web application from the Web option.
4. Enter the name for the project and select the location where you want to create the project folder.
5. Click finish.
6. This will create the folders like src, build and WebContent. WebContent is the folder where we will place all the
dependent libraries and jsp files where as in src we will have Java source files for the application.

Note:- Click here to see the steps in a movie. We are using the latest version of Eclipse 3.2.2. The downloadable zip file is
available on the http://eclipse.org site.

62/148
Your First JSP Page 04/28/09 03:44:52

Configuring Server in Eclipse

Configuring Server in Eclipse


The following are the steps for setting the Tomcat server in the eclipse environment.

1. Select Windows>Preferences from the menu items.


2. Select Server from the explorer options.
3. Click on Installed Runtimes.
4. Click on Add and select the server you need to add. We are using Tomcat so we use Apache object and then
selecting the right version of Tomcat(5.5 in our case).
5. Click on the Next button.
6. Give the Tomcat installed directory path.
7. Click Finish. It will display the Tomcat server setting in the Grid.
8. Click Ok

Note:- Click here to see the steps in a movie.

63/148
Your First JSP Page 04/28/09 03:44:52
Deploy & Run WebApplication

Steps to Deploy And Run Web Application


The following are the steps to run and deploy the web application on the server using the Eclipse IDE. We will create a
index.html file and then run the file in eclipse for testing and deployment.

1. Select New>HTML from the dialog appears after the right clicking the application.
2. Give the file name as index.html
3. Click Finish button.
4. Put the text on the HTML file and save the file.
5. Right Click the project and select Run As option.
6. Select 1.Run on Server from the appeared sub menu.
7. Select the Runtime server and click Finish.
8. Automatically the Tomcat server starts and application is deployed to the server.
9. Eclipse will display the output.

Note:- Click here to see the steps in a movie.

64/148
Your First JSP Page 04/28/09 03:44:52

Your First JSP Page

Your First JSP Page


Let's see how do we create the JSP pages in eclipse. We start with the classic Hello World Application. Steps to create the
JSP page is as follows:-

• Right Click on the Project WebContent.


• Goto New> JSP
• Enter the JSP page name with .jsp extension in the dialog.
• Click Finish

You will see the file is created under the WebContent folder. Enter the following code in the file.

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
<%=Hello World %>
</body>
</html>
Output:-

Hello World

Note:- You have seen the above JSP. The code is written in the <%= %>(expression tags). The next section will explain
the JSP elements more in detail.

65/148
Your First JSP Page 04/28/09 03:44:52

Different JSP tags

Different JSP Tags


There are following basic JSP elements which can be used with the JSP pages.

1. Scriptlet Element.
2. Expression Element.
3. Declaration Element.
4. Comments

The Scriptlet Element


Syntax :-<% Java Code %>

The simplest type of JSP element is the Scriptlet element. A Scriptlet element is simply a section of Java code
encapsulated within the opening and closing JSP tags. The Scriplet is only applicable to the page in which it is declared
and not in the other sub pages. The best part of the JSP is the power of directly using the Java Code with the HTML tags.

Example:- <% if(cond)%> is the sample code for the Scriplet.

Expression Element
Syntax: <%= code %>

The expression tag is used to print the output in the HTML format in the JSP page. In the last section we have just seen
that it is used to output the String object on JSP page.

Declaration Element Syntax


Syntax: <%! code %>

The next type of Scripting element is the Declaration element. The purpose of a Declaration element is to initialize
variables and methods and make them available to other Declarations, Scriptlets, and Expressions.

Comments
Syntax: <%-- comment --%> <!-- comment -->

There are two different types of comments in JSP. The difference between the types of comments is that <%-- --%>
comment is not viewable at the client side but the other one is viewable by selecting the view page source option.

66/148
Your First JSP Page 04/28/09 03:44:52

Scriptlet Example

Scriptlet Example
Lets see the scriplet tag with example. The below example will print the numbers from 1 to 10.

counting.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
Going to Print the Numbers from 1 to 10. <br/>
<% for(int i=1;i<=10;i++){ %>
<%=i %><br>
<%} %>
</body>
</html>

Output:-

67/148
Your First JSP Page 04/28/09 03:44:52

Declaration Tag Exmaple

Declaration Tag Example


Lets see the scriptlet tag with example. The below example has one method named check() to check the odd and even
number and return the String object for the same.

oddeven.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
<%!
public String check(int num){

if(num %2 ==0 ){
return The Number + num + is an even number;
}else{
return The Number + num + is an odd number;
}
}
%>

<% for(int i=1;i<=10;i++){ %>


<%=check(i) %><br>
<%} %>
</body>
</html>
Output:-

68/148
Your First JSP Page 04/28/09 03:44:52

69/148
Your First JSP Page 04/28/09 03:44:52

Directive Elements

Directive Elements
JSP directives are the special tags which are used to send some instructions to the JSP engine. This instruction can be
encoding type of the page, packages to import for the page or the tag library location etc. They do not contain business
logic. They do not modify the out stream. They simply tell the JSP engine how the JSP page should be compiled. The
following table will explain the directive tags which is available in JSP. The coming section will explain the usage and
examples of each tag. Please note the directive tag starts with < %@.

Table for Directive tags

Directive Purpose
The page directive allows several different page-specific
< %@ page%>
attributes to be set.
The include directive used to include the different pages into
<%@ include%> the page. This helps in modularization and reusability of the
JSP pages.
The taglib directive specifies a tag library by which the
<%@ taglib%> standard set of JSP tags can be extended. The tags define in
the taglib is used with normal HTML tags.

70/148
Your First JSP Page 04/28/09 03:44:52

Page Directive Attributes

Page Directive Attributes


The page directive allows several different page-specific attributes to be set. A single JSP page can have multiple page
directives. Page directives always begin with the standard JSP open tag followed by an @ symbol and the keyword page
(<%@ page). For example <%@ page import=java.util.Calendar %> The above page directive imports the
java.utilCalendar class. The below table will explain all the page attributes and their purpose.

Attribute Description
The buffer attribute specifies the buffer size for
buffer
buffered JSP page.
By default it is set to true. It flushes the output
autoFlush
when the buffer is full in buffered JSP pages.
It is used to define the response encoding type
contentType that JSP produces as well as the MIME type of
response.
This attribute is used to specify the URL where
errorPage
the control is transferred in case error occurred.
By default it is false. If set to true then this tells
the JSP engine that this page is an error page and
isErrorPage
can be called from some other page in case of
any exception occurred.
it specified the super class of the JSP page. This
extends attribute is not recommended to use. If it is not
specified then the JSP speed is much higher.
It is used to import the various Java classes. It is
same as import statement in Java program.
import
Multiple imports can be separate with comma in
same attribute.
It is used to specify the information regarding
info
the JSP page.
By default is set to true. This tells the JSP
engine to process the simultaneously requests
isThreadSafe
coming for the page. For better performance this
value should not be changed.
It specifies the language for the JSP page.
language
Normally the value is Java.
This attribute tells the JSP engine whether the
session session object need to be created for the JSP
page or not. The default value is true.
Note:- The next section will show the use of some of the above attributes.

71/148
Your First JSP Page 04/28/09 03:44:52

Page Directive Example

Page Directive Example


Lets see how to declare and use some page directive attributes. The below example will explain the use of the import and
response encoding type

<%@ page language=java contentType=text/html; charset=ISO-8859-1 buffer=16kb


pageEncoding=ISO-8859-1%>
<%@ page import=java.util.Date; session=true%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
</head>
<body> Current Time is <br>
<%= new Date().getTime() %>
</body>
</html>

Output without Import

72/148
Your First JSP Page 04/28/09 03:44:52

Output with Import

73/148
Your First JSP Page 04/28/09 03:44:52

Include Directive Example

Include Directive Example


Lets see how to use the <@include to include the different files and generate the single output to the user. We will create
firstpage.jsp and secondpage jsp files. The second file is included in the first file.

firstpage.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
This is First Page.
<br>
Including the Second Page Here <br>
<%@include file=secondpage.jsp%>
</body>
</html>

secondpage.jsp

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN


http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head>
<body>
This is Second Page
</body>
</html>

Output:- Calling secondpage.jsp

74/148
Your First JSP Page 04/28/09 03:44:52

Calling firstpage.jsp

75/148
Your First JSP Page 04/28/09 03:44:52

Stanadard Actions

Standard Actions
The JSP specifications define six standard actions, which can be grouped into two distinct categories. The two categories
of Actions are as follows:-

• Resource Actions.
• JavaBean Actions

The Resource Actions

Resource actions specify external resources that should be used with the JSP page. The following actions comes under this
category.

• <jsp:include>:- The include action can be used to insert the output of both static and dynamic pages into the current
page.
• <jsp:forward>:- The forward action terminates the action of the current page and forwards the request to another
resource, such as a static page, another JSP page, or a Java Servlet.
• <jsp:plugin>:- The plugin action is used to insert Java components into a JSP page.

The JavaBean Actions

The JavaBean actions are used to access server side JavaBeans within a JSP page. JavaBeans are the components which
used to make the structured data under a single name. JavaBean has some properties which are accessed with the
setter/getter method defined in the JavaBean class. The following tags are used to communicate with the JavaBeans:-

• <jsp:useBean>:-The useBean action finds or creates an instance of an object. It also associates this object with an
implicit object specified by the scope attribute (page, request, session, and application).
• <jsp:setProperty>:- The setProperty action sets the properties of a Bean.
• <jsp:getProperty>:-The getProperty action is used to retrieve the value of a given property and print it.

76/148
Your First JSP Page 04/28/09 03:44:52

<jsp:include> Action Example

<jsp:include> Action Example


Lets see how to use the <jsp:include to include the different files and generate the single output to the user. We will create
includeexample.jsp and secondpage.jsp files. The second file is included in the first file.

includeexample.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
This is First Page.
<br>
Including the Second Page Here <br>
<jsp:include page=secondpage.jsp/>
</body>
</html>

secondpage.jsp

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN


http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head>
<body>
This is Second Page
</body>
</html>

Output:- Calling secondpage.jsp

77/148
Your First JSP Page 04/28/09 03:44:52

Calling includeexample.jsp

78/148
Your First JSP Page 04/28/09 03:44:52
Comparison Between include Directive And include Action

Comparison Between include Directive And include Action


Although the <@include and <jsp:include both are used to add the inner pages into the outer pages but both are different
in the way the JSP handles. The following are the differences in both :-

<@include directive <jsp:include Action


file attribute is present in the directive page is the attribute used in the jsp:include.
The <jsp;param> is the tag which is used to pass the values to
The values can be passes only by the queryString.
page. This makes code a little cleaner and easy to understand.
The content is included at the runtime or request time, which
The content of the included page gets compiled at the compile time
the statement encountered for the inclusion then control is pas
and make as inline. So if we modify the inner page we need to
inner page and get the content. So there is no recompilation n
recompile all the pages in order to get the changes.
inner page modifies.
As the page is inline so the performance in the include directive is
The extra page need to compile so the response time is increa
more.

79/148
Your First JSP Page 04/28/09 03:44:52

<jsp:forward> example

<jsp:forward> example
Lets create two pages one is where the user need to forward i.e. forward.jsp and other one is from which the user is
forwarded without knowing i.e forwardexample.jsp

forward.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
This is Forwarded page.
</body>
</html>
forwardexample.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
<jsp:forward page=forward.jsp/>
</body>
</html>

Output:-

80/148
Your First JSP Page 04/28/09 03:44:52

81/148
Your First JSP Page 04/28/09 03:44:52

JavaBean Actions Example

JavaBean Actions Example


Lets consider we have a bean names Person which has name and age as its properties. The below example will set and get
the properties of the Person bean in JSP.

Person.java

package com.visualbuilder.beans;

public class Person {


private String name;
private int age;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}
}
beanexample.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id=person class=com.visualbuilder.beans.Person/>
<jsp:setProperty name=person property=name value=Chris/>
<jsp:setProperty name=person property=age value=18/>
The name is :- <jsp:getProperty name=person property=name /><br/>
The age is :- <jsp:getProperty name=person property=age /><br/>
</body>
</html>

82/148
Your First JSP Page 04/28/09 03:44:52

Output:-

83/148
Your First JSP Page 04/28/09 03:44:52

Scopes in JSP

Bean Scopes in JSP


We have just seen the how beans can be used in the JSP page. The scope attribute in the <jsp:useBean> tag can be used to
define the scope and lifetime of the object created by the action. There are four scope available in the JSP.

1. page:- Objects with page scope are accessible only in that page and can not go beyond it. By default the scope is
request.
2. request:- Objects with request scope can persist with the request object and valid only till the request is valid.
3. session:- Objects defined with session scopes will be available with the session. So for shopping cart or ecommerce
application where the state need to managed we can use this cope more frequently.
4. application:- Objects defined with application scopes will be available till the application remains in the memory.
All static objects whose data does not change frequently will be defined with the application scope.

The coming section will explain the example for the request scope. The session and application scopes will be discussed
later on.

84/148
Your First JSP Page 04/28/09 03:44:52

Request Bean Scope Example

Request Bean Scope Example


The previous example is used and extend it to the request scope. We will set the property in one page and get the property
in the next page. From first page we will forward the request to second page.

requestbeanscope.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id=person class=com.visualbuilder.beans.Person scope=request/>
<jsp:setProperty name=person property=name value=Chris/>
<jsp:setProperty name=person property=age value=18/>
<jsp:forward page=requestbeanexample1.jsp/>
</body>
</html>
requestbeanscope1.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id=person class=com.visualbuilder.beans.Person scope=request/>
The name is :- <jsp:getProperty name=person property=name /><br/>
The age is :- <jsp:getProperty name=person property=age /><br/>
</body>
</html>
Output:-

85/148
Your First JSP Page 04/28/09 03:44:52

86/148
Your First JSP Page 04/28/09 03:44:52

Implicit Objects

Implicit Objects
The Servlet also creates several objects to be used by the JSP engine. These objects are available for the JSP developer
and they can use the objects in the JSP files without declaring the objects in the JSP. The following table will explain all
the implicit objects available in the JSP pages.

Object Description
The out object is an instantiation of a javax.servlet.jsp.JspWriter object. This
out object may represent a direct reference to the output stream, a filtered stream, or a
nested JspWriter from another JSP.
Each time a client requests a page the JSP engine creates a new object to represent
that request. This new object is an instance of
request
javax.servlet.http.HttpServletRequest and is given parameters describing the
request.
The response object is an instance of javax.servlet.http.HttpServletResponse and is
response
used to send the response to the browser.
The application is same as the ServletContext object in Servlet. It has the same
application
methods and interfaces that the ServletContext object have in Servlets.
The session object is an instance of HttpSession and used to track information
session
about a particular client. Each client has one global session object.
The pageContext object is used to represent the entire JSP page and contains
pageContext
information about the directives issued to the JSP page.
The config object is an instantiation of javax.servlet.ServletConfig. It has the
config
same methods and interfaces that the ServletConfig object have in Servlet.
The error handling methods described in . It is available only when the previous
JSP page throws an uncaught exception and the <%@ page errorPage=... %> tag
exception
was used. The exception object is a wrapper containing the exception thrown
from the previous page.
This object is an actual reference to the instance of the page. In other words we can
page
say , page object equal to this object.
The coming section will explain the examples of individual object.

87/148
Your First JSP Page 04/28/09 03:44:52

Out Object Example

Out Object Example


We start now understanding the implicit object with the help of examples. First object is out. The next example will show
how do we format the output using the out object.

outexample.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
<%for(int i=0;i<10;i++){
for(int j=0;j<=i;j++){
out.print(*);
}
out.println(<br>);
}
%>
</body>
</html>
Output:-

88/148
Your First JSP Page 04/28/09 03:44:52

89/148
Your First JSP Page 04/28/09 03:44:52

Request Object Example

Request Object Example


The request object is created for each request and once the response is submitted then it gets destroyed. The request object
is used to pass the information from one page to the other page if the pages are getting invoked during the request
lifecycle. The below example will print all the request attributes as well as it gets the information passed from outer page
to inner page.

requestexample.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
<body>
<p><font size=5>Request Information:</font></p>
<table border=1 cellpadding=0 cellspacing=1>
<tr>
<td width=33%><b>Request Method:</b></td><td
width=67%><%=request.getMethod()%></td>
</tr>
<tr>
<td width=33%><b>Request URI:</b></td><td
width=67%><%=request.getRequestURI()%></td>
</tr>
<tr>
<td width=33%><b>Request Protocol:</b></td><td
width=67%><%=request.getProtocol()%></td>
</tr>
<tr>
<td width=33%><b>Path Info:</b></td><td
width=67%><%=request.getPathInfo()%></td>
</tr>
<tr>
<td width=33%><b>Path translated:</b></td><td
width=67%><%=request.getPathTranslated()%></td>
</tr>
<tr>
<td width=33%><b>Query String:</b></td><td
width=67%><%=request.getQueryString()%></td>
</tr>
<tr>
<td width=33%><b>Content length:</b></td><td

90/148
Your First JSP Page 04/28/09 03:44:52

width=67%><%=request.getContentLength()%></td>
</tr>
<tr>
<td width=33%><b>Content type:</b></td><td
width=67%><%=request.getContentType()%></td>
</tr>
<tr>
<td width=33%><b>Server name:</b></td><td
width=67%><%=request.getServerName()%></td>
</tr>
<tr>
<td width=33%><b>Server port:</b></td><td
width=67%><%=request.getServerPort()%></td>
</tr>
<tr>
<td width=33%><b>Remote user:</b></td><td
width=67%><%=request.getRemoteUser()%></td>
</tr>
<tr>
<td width=33%><b>Remote address:</b></td><td
width=67%><%=request.getRemoteAddr()%></td>
</tr>
<tr>
<td width=33%><b>Remote host:</b></td><td
width=67%><%=request.getRemoteHost()%></td>
</tr>
<tr>
<td width=33%><b>Authorization scheme:</b></td><td
width=67%><%=request.getAuthType()%></td>
</tr>
</table>
<%request.setAttribute(information,This is information passed from outer page);%>
<jsp:include page=requestinner.jsp/>

</body>
</html>
requestinner.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
The Passed value from the Outer page is :-&nbsp;
<%=request.getAttribute(information)%>

91/148
Your First JSP Page 04/28/09 03:44:52

</body>
</html>
Output:-

92/148
Your First JSP Page 04/28/09 03:44:52

Response Object Example

Response Object Example


The response object is used to send and set the information at client side. The cookies are the small files used to save the
information in the client machine which can be used for some further actions and state maintenance. The below example
will set one cookie and then send the user to other page where we access the cookie value.

responseexample.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
<% Cookie cookie = new Cookie (testcookie,Visualbuilder);
cookie.setMaxAge(365 * 24 * 60 * 60);
response.addCookie(cookie);
response.sendRedirect(getcookie.jsp);
%>

</body>
</html>
getcookie.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
<%

Cookie[] cookies= request.getCookies();


for(int i=0;i<cookies.length;i++){
if(cookies[i].getName().equalsIgnoreCase(testcookie)){
out.println(Cookie Value is + cookies[i].getValue());
}
}
%>
</body>

93/148
Your First JSP Page 04/28/09 03:44:52

</html>
Output:-

94/148
Your First JSP Page 04/28/09 03:44:52

Session Object Example

Session Object Example


The session object is an instance of HttpSession and used to track information about a particular client. Each client has
one global session object. When user send the fist request to the JSP engine it will issue a session id to track the
information for the transaction. The below example will show the session id as well as the count which shows how many
times the page is accessed during the current session.

sessionexample.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
Sesion id for the Session is :- <%=session.getId() %><br>
<%
if (session.getAttribute(count) != null){
int count = Integer.parseInt((String)session.getAttribute(count));
count++;
out.println(The number of times the page accessed + count );
session.setAttribute(count,String.valueOf(count));
}else{
session.setAttribute(count,1);
out.println(The page is accessed for the first time);
}

%>
</body>
</html>
Output:- When user refershed the page with in same session.

95/148
Your First JSP Page 04/28/09 03:44:52

When user opens a new browser a new session id is generated.

96/148
Your First JSP Page 04/28/09 03:44:52

Application Object Example

Application Object Example


Unlike session object which created separately for each client browser, the application object created one for whole
application. This object remains in the memory once the application is initialized and destroyed once the application will
be removed from the server or the server shuts down. This is a static object which is shared by all the clients. Application
objects normally used to cache the data for better performance. We change the session example with the application object
and see what will be happen when we run the page in multiple browsers.

applicationexample.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
Sesion id for the Session is :- <%=session.getId() %><br>
<%
if (session.getAttribute(count) != null){
int count = Integer.parseInt((String)session.getAttribute(count));
count++;
out.println(The number of times the page accessed + count );
session.setAttribute(count,String.valueOf(count));
}else{
session.setAttribute(count,1);
out.println(The page is accessed for the first time);
}

%>
</body>
</html>
Output:- When user refershed the page.

When user opens a new browser.

97/148
Your First JSP Page 04/28/09 03:44:52

98/148
Your First JSP Page 04/28/09 03:44:52

Working With Forms-2

Working With HTML Form -2


The previous section has explained what all controls are used in HTML for creating the forms. Lets see with the help of
below example how do we get the form data in JSP page which is send by the user.

We need to first define which JSP page should be accessed when this form is submitted. This can be achieved by the
action attribute in the <form>. For example:- <form action=/login.jsp> will generate a request for the login.jsp page
when the submit button will be clicked for the form.

We will be creating the input1.jsp file which will show the data which user has sent from login.html page from the
previous example.

Example:-

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN


http://www.w3.org/TR/html4/loose.dtd>
<html>

<head>
<meta http-equiv=Content-Language content=en-us>
<meta http-equiv=Content-Type content=text/html; charset=windows-1252>
<title>Login Form</title>
</head>

<body>

<p align=left><b>Login Form

</b></p>

<form method=POST action=login.jsp name=loginForm>

<table border=1 width=50% cellspacing=1 cellpadding=0 id=table1>


<tr>
<td width=50%>&nbsp;Login Name</td>
<td><input type=text name=loginName size=20></td>
</tr>
<tr>
<td width=50%>Password</td>
<td><input type=password name=password size=20></td>
</tr>
</table>
<p><input type=submit value=Submit name=B1><input type=reset value=Reset
name=B2></p>
</form>

</body>

99/148
Your First JSP Page 04/28/09 03:44:52

</html>
JSP page:-

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Login Form Data</title>
</head>
<body>
<b>Submitted Values are </b>
<table border=1 width=50% cellspacing=1 cellpadding=0 id=table1>
<tr>
<td width=50%>&nbsp;Login Name</td>
<td><%=request.getParameter(loginName) %></td>
</tr>
<tr>
<td width=50%>Password</td>
<td><%=request.getParameter(password) %></td>
</tr>
</table>
</body>
</html>
Output:- The following screen will be displayed when login form will gets submitted.

100/148
Your First JSP Page 04/28/09 03:44:52

Exception Object Example

Exception Object Example


Lets see how the exception object can be used in the JSP page. In the below example we will have two JSP files. Firstly
which has errorPage attribute is set to second page and throws the exception. The second file has the isErrorpage set to
true and displays the exception with the help of exception implicit object.

exception.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1 errorPage=exceptionfirst.jsp%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
<%
String str=null;
str.charAt(0);
%>
</body>
</html>
exceptionfirst.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1 isErrorPage=true%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
The exception which occured during the processing is :- <br>
<%=exception.toString() %>
</body>
</html>
Output:-

101/148
Your First JSP Page 04/28/09 03:44:52

Note:- Rest implicit objects will be discussed as and when their requirements occured in the applications.

102/148
Your First JSP Page 04/28/09 03:44:52

Working With HTML Form

Working With HTML Form -1


HTML pages have also used to create the forms which gather the information from user in the interactive web pages. In
HTML we have <form> tag and form controls which are used to create the forms in web pages. All the controls related to
a particular form need to define inside the <form></form> tag.

The following table will explain the basic form controls available for form building in html.

Control Description Control Appearance C


The control is used to accept the text values
Text Box <INPUT type=text na
from the user.
Submit is a special kind of button and used to
Submit Button <INPUT type=submi
send the form control information to the server.
Reset will remove all the control values and
Reset Button <INPUT type=reset n
make them default.
Normal buttons are used to control some flows
Normal Button programitically. We will discuss the controls <INPUT type=button
later in coming sections.
Used to show the user some multiple options
Checkbox <INPUT type=check
which user can choose as per his interest.
Radio button is used to show various possible
Radio button options to the user and permit it to select only <INPUT type=radio
one
<select name=sel1 >
Select List Select list the combo list shows to user. </option><option
value=2>2</option>.
Used to show the user a file dialog and select the
File Select dialog. This generally used where user want to <INPUT type=file na
select some files and upload it to server.
It will be used to pass some secret values which
Hidden fields <INPUT type=hidden
is not shown to user with the other form values.
Password field will be used to accept the
Password field <INPUT type=passw
passwords.
Note:- The browser will always submit the data as name/value pair from form. So all the controls need to have the name
attribute whose data you need to pass to the server.

The below is the sample login form:-

HTML page:-

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN


http://www.w3.org/TR/html4/loose.dtd>
<html>

<head>
<meta http-equiv=Content-Language content=en-us>

103/148
Your First JSP Page 04/28/09 03:44:52

<meta http-equiv=Content-Type content=text/html; charset=windows-1252>


<title>Login Form</title>
</head>

<body>

<p align=left><b>Login Form

</b></p>

<form name=loginForm >

<table border=1 width=50% cellspacing=1 cellpadding=0 id=table1>


<tr>
<td width=50%>&nbsp;Login Name</td>
<td><input type=text name=loginName size=20></td>
</tr>
<tr>
<td width=50%>Password</td>
<td><input type=password name=password size=20></td>
</tr>
</table>
<p><input type=submit value=Submit name=B1><input type=reset value=Reset
name=B2></p>
</form>

</body>

</html>
Output:-The above code will display the login form as follows:-

104/148
Your First JSP Page 04/28/09 03:44:52

Working With Form Contd.

Working With Form Contd.


The previous section has explained what all controls are used in HTML for creating the forms. Lets see with the help of
below example how do we get the form data in JSP page which is send by the user.

We need to first define which JSP page should be accessed when this form is submitted. This can be achieved by the
action attribute in the <form>. For example:- <form action=/login.jsp> will generate a request for the login.jsp page
when the submit button will be clicked for the form.

We will be creating the input1.jsp file which will show the data which user has sent from login.html page from the
previous example.

Example:-

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN


http://www.w3.org/TR/html4/loose.dtd>
<html>

<head>
<meta http-equiv=Content-Language content=en-us>
<meta http-equiv=Content-Type content=text/html; charset=windows-1252>
<title>Login Form</title>
</head>

<body>

<p align=left><b>Login Form

</b></p>

<form method=POST action=login.jsp name=loginForm>

<table border=1 width=50% cellspacing=1 cellpadding=0 id=table1>


<tr>
<td width=50%>&nbsp;Login Name</td>
<td><input type=text name=loginName size=20></td>
</tr>
<tr>
<td width=50%>Password</td>
<td><input type=password name=password size=20></td>
</tr>
</table>
<p><input type=submit value=Submit name=B1><input type=reset value=Reset
name=B2></p>
</form>

105/148
Your First JSP Page 04/28/09 03:44:52

</body>

</html>
JSP page:-

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Login Form Data</title>
</head>
<body>
<b>Submitted Values are </b>
<table border=1 width=50% cellspacing=1 cellpadding=0 id=table1>
<tr>
<td width=50%>&nbsp;Login Name</td>
<td><%=request.getParameter(loginName) %></td>
</tr>
<tr>
<td width=50%>Password</td>
<td><%=request.getParameter(password) %></td>
</tr>
</table>
</body>
</html>
Output:- The following screen will be displayed when login form will gets submitted.

106/148
Your First JSP Page 04/28/09 03:44:52

Form Validation -1

Form Validation -1
Form validation is the process of checking that a form has been filled in correctly before it is processed. For example:- If
user has asked to give the name and he enter some @! special symbols then it is not valid as these are not the correct
name. There are two mainly two types of form validations: server-side (using JSP ASP, etc), and client-side (usually done
using JavaScript). The following is the difference between the serverside and client side validations: -

Client side validation runs in the browser to check that the form values are of the correct type. JavaScript should always
be used on the client side
since it is supported by both Netscape and IE. (VBScript is supported only by IE). where as Server side validation checks
the code that is submitted to make sure it is correct.

The following example will show how do we use the javascript to validate the login form.

Example:-

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN


http://www.w3.org/TR/html4/loose.dtd>
<html>

<head>
<meta http-equiv=Content-Language content=en-us>
<meta http-equiv=Content-Type content=text/html; charset=windows-1252>
<title>Registration Form</title>
</head>
<script>
function validateForm(form){

if(form.firstName.value==''){
alert (First Name can not be blank);
return false;
}
if(form.lastName.value==''){
alert (Last Name can not be blank);
return false;
}
if(form.introduction.value==''){
alert (Introduce Yourself can not be blank);
return false;
}
if(form.phone.value==''){
alert (Phone can not be blank);
return false;
}
if(form.address.value==''){
alert (Address can not be blank);
return false;
}

107/148
Your First JSP Page 04/28/09 03:44:52

if(form.city.value==''){
alert (City can not be blank);
return false;
}
if(form.state.value==''){
alert (State can not be blank);
return false;
}
}
</script>
<body>

<p align=left><b>Registration Form</b></p>

<form name=registerationForm method=POST action=validateRegistration.jsp


onsubmit=return validateForm(document.registerationForm); >

<table border=1 width=70% cellspacing=1 cellpadding=0 id=table1>


<tr>
<td width=50%>First Name</td>
<td><input type=text name=firstName size=20></td>
</tr>
<tr>
<td width=50%>Last Name</td>
<td><input type=text name=lastName size=20></td>
</tr>
<tr>
<td width=50%>Introduce Yourself</td>
<td><textarea name=introduction cols=40 rows=10></textarea></td>
</tr>
<tr>
<td width=50%>Gender</td>
<td><input type=radio value=V1 checked name=radio1>male
<input type=radio name=radio1 value=V2>female</td>
</tr>
<tr>
<td width=50%>Phone</td>
<td><input type=text name=phone size=20></td>
</tr>
<tr>
<td width=50%>Address</td>
<td><input type=text name=address size=20></td>
</tr>
<tr>
<td width=50%>City</td>
<td><input type=text name=city size=20></td>
</tr>
<tr>
<td width=50%>State</td>
<td><input type=text name=state size=20></td>

108/148
Your First JSP Page 04/28/09 03:44:52

</tr>
<tr>
<td width=50%>Country</td>
<td><select size=1 name=country>
<option selected value=United Kingdom>United Kingdom</option>
<option>USA</option>
<option>Other</option>
</select></td>
</tr>
</table>
<p><input type=submit value=Submit name=B1><input type=reset value=Reset
name=B2></p>
</form>

</body>

</html>
Output:-

109/148
Your First JSP Page 04/28/09 03:44:52

110/148
Your First JSP Page 04/28/09 03:44:52

Form Validation-2

Form Validation-2
Lets see with the help of below example how the same validations, which is implemented in the JavaScript in the previous
example, will be implemented in the JSP page.

Example:-

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN


http://www.w3.org/TR/html4/loose.dtd>
<html>

<head>
<meta http-equiv=Content-Language content=en-us>
<meta http-equiv=Content-Type content=text/html; charset=windows-1252>
<title>Registration Form</title>
</head>

<body>

<p align=left><b>Registration Form</b></p>

<form name=registerationForm method=POST action=validateRegistrationWithBean.jsp>

<table border=1 width=70% cellspacing=1 cellpadding=0 id=table1>


<%
String errors=(String)request.getAttribute(errors);
if(errors != null && errors.trim().length()>0){
out.println(<tr><td colspan='2'>The following are the errors with given
data<br>+errors+</td></tr>);
}
%>
<tr>
<td width=50%>First Name</td>
<td><input type=text name=loginName size=20
value=<%=request.getParameter(loginName)!=null?request.getParameter(loginName):%>></td>
</tr>
<tr>
<td width=50%>Last Name</td>
<td><input type=text name=password size=20
value=<%=request.getParameter(password)!=null?request.getParameter(password):%>></td>
</tr>
<tr>
<td width=50%>Introduce Yourself</td>
<td><textarea name=intro cols=40
rows=10><%=request.getParameter(intro)!=null?request.getParameter(intro):%></textarea></td>
</tr>
<tr>
<td width=50%>Gender</td>

111/148
Your First JSP Page 04/28/09 03:44:52

<td>

<% if(request.getParameter(gender)==null || request.getParameter(gender).equals(male)){ %>


<input type=radio value=male checked name=gender>male
<input type=radio name=gender value=female>female
<%}else{ %>
<input type=radio value=male name=gender>male
<input type=radio name=gender checked value=female>female
<%} %>
</td>

</tr>
<tr>
<td width=50%>Phone</td>
<td><input type=text name=phone size=20
value=<%=request.getParameter(phone)!=null?request.getParameter(phone):%>></td>
</tr>
<tr>
<td width=50%>Address</td>
<td><input type=text name=address size=20
value=<%=request.getParameter(address)!=null?request.getParameter(address):%>></td>
</tr>
<tr>
<td width=50%>City</td>
<td><input type=text name=city size=20
value=<%=request.getParameter(city)!=null?request.getParameter(city):%>></td>
</tr>
<tr>
<td width=50%>State</td>
<td><input type=text name=state size=20
value=<%=request.getParameter(state)!=null?request.getParameter(state):%>></td>
</tr>
<tr>
<td width=50%>Country</td>
<td><select size=1 name=country>
<option selected value=United Kingdom>United Kingdom</option>
<option value=USA>USA</option>
<option value=other>Other</option>
</select></td>
</tr>
</table>
<p><input type=submit value=Submit name=B1><input type=reset value=Reset name=B2></p>
</form>

</body>

</html>
Validation JSP File is as follows:-

112/148
Your First JSP Page 04/28/09 03:44:52

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head>
<body>
<%
String loginName=request.getParameter(loginName);
String password=request.getParameter(password);
String intro=request.getParameter(intro);
String gender=request.getParameter(R1);
String phone=request.getParameter(phone);
String address=request.getParameter(address);
String city=request.getParameter(city);
String state=request.getParameter(state);
String country=request.getParameter(country);
String errors=;

if(loginName ==null || loginName.trim().length() ==0){


errors=errors+<li>Please enter the Login Name<br>;
}
if(password ==null || password.trim().length() ==0){
errors=errors+<li>Please enter the Password<br>;
}
if(intro ==null || intro.trim().length() ==0){
errors=errors+<li>Please enter the introduction<br>;
}
if(gender ==null || gender.trim().length() ==0){
errors=errors+<li>Please select Gender<br>;
}
if(phone ==null || phone.trim().length() ==0){
errors=errors+<li>Please enter phone<br>;
}
if(address ==null || address.trim().length() ==0){
errors=errors+<li>Please enter address<br>;
}
if(city ==null || city.trim().length() ==0){
errors=errors+<li>Please enter city<br>;
}
if(state ==null || state.trim().length() ==0){
errors=errors+<li>Please enter state<br>;
}
if(country ==null || country.trim().length() ==0){
errors=errors+<li>Please enter country<br>;
}
if( errors.trim().length() >0){

113/148
Your First JSP Page 04/28/09 03:44:52

request.setAttribute(errors,errors);
%>
<jsp:forward page=registerwithvalidation.jsp></jsp:forward>
<%
}
%>
<h1>The given data is Valid.</h1>
</body>
</html>
Output:-

114/148
Your First JSP Page 04/28/09 03:44:52

115/148
Your First JSP Page 04/28/09 03:44:52

Using Beans for Form Data -1

Using Beans for Form Data -1


Most of the time form contains more than one fields. Then it is very difficult to use the request object for the form
validation and controlling the fields. To solve the issue we have Java Beans which are used to create the structures which
capture the data. We have seen initially that JSP has explicit tags to set and get the data from the Java Beans. Lets see how
Bean is used to capture and validate the Registration form data. this also makes our JSP code easy to read as the whole
java code is moved into the Bean class.

Example:-

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN


http://www.w3.org/TR/html4/loose.dtd>
<html>

<head>
<meta http-equiv=Content-Language content=en-us>
<meta http-equiv=Content-Type content=text/html; charset=windows-1252>
<title>Registration Form</title>
</head>

<body>

<p align=left><b>Registration Form</b></p>

<form name=registerationForm method=POST action=validateRegistrationWithBean.jsp>

<table border=1 width=70% cellspacing=1 cellpadding=0 id=table1>


<%
String errors=(String)request.getAttribute(errors);
if(errors != null && errors.trim().length()>0){
out.println(<tr><td colspan='2'>The following are the errors with given
data<br>+errors+</td></tr>);
}
%>
<tr>
<td width=50%>First Name</td>
<td><input type=text name=loginName size=20
value=<%=request.getParameter(loginName)!=null?request.getParameter(loginName):%>></td>
</tr>
<tr>
<td width=50%>Last Name</td>
<td><input type=text name=password size=20
value=<%=request.getParameter(password)!=null?request.getParameter(password):%>></td>
</tr>
<tr>
<td width=50%>Introduce Yourself</td>
<td><textarea name=intro cols=40
rows=10><%=request.getParameter(intro)!=null?request.getParameter(intro):%></textarea></td>

116/148
Your First JSP Page 04/28/09 03:44:52

</tr>
<tr>
<td width=50%>Gender</td>
<td>

<% if(request.getParameter(gender)==null || request.getParameter(gender).equals(male)){ %>


<input type=radio value=male checked name=gender>male
<input type=radio name=gender value=female>female
<%}else{ %>
<input type=radio value=male name=gender>male
<input type=radio name=gender checked value=female>female
<%} %>
</td>

</tr>
<tr>
<td width=50%>Phone</td>
<td><input type=text name=phone size=20
value=<%=request.getParameter(phone)!=null?request.getParameter(phone):%>></td>
</tr>
<tr>
<td width=50%>Address</td>
<td><input type=text name=address size=20
value=<%=request.getParameter(address)!=null?request.getParameter(address):%>></td>
</tr>
<tr>
<td width=50%>City</td>
<td><input type=text name=city size=20
value=<%=request.getParameter(city)!=null?request.getParameter(city):%>></td>
</tr>
<tr>
<td width=50%>State</td>
<td><input type=text name=state size=20
value=<%=request.getParameter(state)!=null?request.getParameter(state):%>></td>
</tr>
<tr>
<td width=50%>Country</td>
<td><select size=1 name=country>
<option selected value=United Kingdom>United Kingdom</option>
<option value=USA>USA</option>
<option value=other>Other</option>
</select></td>
</tr>
</table>
<p><input type=submit value=Submit name=B1><input type=reset value=Reset name=B2></p>
</form>

</body>

</html>

117/148
Your First JSP Page 04/28/09 03:44:52

package com.visualbuilder.beans;

import javax.servlet.http.HttpServletRequest;

public class RegistrationBean {


String loginName;
String password;
String intro;
String gender;
String phone;
String address;
String city;
String state;
String country;
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {

118/148
Your First JSP Page 04/28/09 03:44:52

this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public void validate(HttpServletRequest request){
String errors=;

if(loginName ==null || loginName.trim().length() ==0){


errors=errors+<li>Please enter the Login Name<br>;
}
if(password ==null || password.trim().length() ==0){
errors=errors+<li>Please enter the Password<br>;
}
if(intro ==null || intro.trim().length() ==0){
errors=errors+<li>Please enter the introduction<br>;
}
if(gender ==null || gender.trim().length() ==0){
errors=errors+<li>Please select Gender<br>;
}
if(phone ==null || phone.trim().length() ==0){
errors=errors+<li>Please enter phone<br>;
}
if(address ==null || address.trim().length() ==0){
errors=errors+<li>Please enter address<br>;
}
if(city ==null || city.trim().length() ==0){
errors=errors+<li>Please enter city<br>;
}
if(state ==null || state.trim().length() ==0){
errors=errors+<li>Please enter state<br>;
}
if(country ==null || country.trim().length() ==0){
errors=errors+<li>Please enter country<br>;
}

119/148
Your First JSP Page 04/28/09 03:44:52

if( errors.trim().length() >0){


request.setAttribute(errors,errors);
}
}
}

120/148
Your First JSP Page 04/28/09 03:44:52

Using Beans for Form Data -2

Using Beans for Form Data -2


The below is the code for the validate file. Now the JSP is setting the properties in the bean and calling the validate
method for the validations.

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head>
<body>
<jsp:useBean id=bean class=com.visualbuilder.beans.RegistrationBean/>
<jsp:setProperty name=bean property=*/>
<%
com.visualbuilder.beans.RegistrationBean
register=(com.visualbuilder.beans.RegistrationBean)pageContext.getAttribute(bean);
register.validate(request);
String errors= (String)request.getAttribute(errors);
if( errors.trim().length() >0){
%>
<jsp:forward page=registerwithbean.jsp></jsp:forward>
<%
}
%>
<h1>The given data is Valid.</h1>
</body>
</html>
Output:- When form is submitted with invalid data then following screen will be displayed.

121/148
Your First JSP Page 04/28/09 03:44:52

122/148
Your First JSP Page 04/28/09 03:44:52

Mutipage Forms-1

Mutipage Forms-1
Some forms are very long and logically divided into separate long sections. To handle those forms in the JSP is to scatter
the form in multiple pages and then show the user those page in sequence. The muti page forms also used to show for
showing the wizards to the user which helps the user to show only the question based on the answers collected in the
previous sections. The previous example of registration is now divided into two parts and we have created the two pages
for a single form.

Example:-

mutipage1.jsp

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN


http://www.w3.org/TR/html4/loose.dtd>
<html>

<head>
<meta http-equiv=Content-Language content=en-us>
<meta http-equiv=Content-Type content=text/html; charset=windows-1252>
<title>Registration Form</title>
</head>

<body>

<p align=left><b>Registration Form</b></p>


<jsp:useBean id=bean class=com.visualbuilder.beans.RegistrationBean scope=session/>
<%
com.visualbuilder.beans.RegistrationBean
register=(com.visualbuilder.beans.RegistrationBean)session.getAttribute(bean);
%>
<form name=registerationForm method=POST action=multipage2.jsp>

<table border=1 width=70% cellspacing=1 cellpadding=0 id=table1>


<%
String errors=(String)request.getAttribute(errors);
if(errors != null && errors.trim().length()>0){
out.println(<tr><td colspan='2'>The following are the errors with given
data<br>+errors+</td></tr>);
}
%>
<tr>
<td width=50%>First Name</td>
<td><input type=text name=loginName size=20
value=<%=register.getLoginName()!=null?register.getLoginName():%>></td>
</tr>
<tr>
<td width=50%>Last Name</td>
<td><input type=text name=password size=20

123/148
Your First JSP Page 04/28/09 03:44:52

value=<%=register.getPassword()!=null?register.getPassword():%>></td>
</tr>
<tr>
<td width=50%>Introduce Yourself</td>
<td><textarea name=intro cols=40
rows=10><%=register.getIntro()!=null?register.getIntro():%></textarea></td>
</tr>
<tr>
<td width=50%>Gender</td>
<td>

<% if(register.getGender()==null || register.getGender().equals(male)){ %>


<input type=radio value=male checked name=gender>male
<input type=radio name=gender value=female>female
<%}else{ %>
<input type=radio value=male name=gender>male
<input type=radio name=gender checked value=female>female
<%} %>
</td>

</tr>

</table>
<p><input type=submit value=Submit name=B1><input type=reset value=Reset
name=B2></p>
</form>

</body>

</html>
Form :-

124/148
Your First JSP Page 04/28/09 03:44:52

125/148
Your First JSP Page 04/28/09 03:44:52

Mutipage Forms-2

Mutipage Forms-2
This is the second page of the form. The following is the code and form.

multipage2.jsp

<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN


http://www.w3.org/TR/html4/loose.dtd>
<html>

<head>
<meta http-equiv=Content-Language content=en-us>
<meta http-equiv=Content-Type content=text/html; charset=windows-1252>
<title>Registration Form</title>
</head>

<body>

<p align=left><b>Registration Form</b></p>


<jsp:useBean id=bean class=com.visualbuilder.beans.RegistrationBean scope=session/>
<jsp:setProperty name=bean property=loginName/>
<jsp:setProperty name=bean property=password/>
<jsp:setProperty name=bean property=gender/>
<jsp:setProperty name=bean property=intro/>
<form name=registerationForm method=POST action=multipage3.jsp>

<table border=1 width=70% cellspacing=1 cellpadding=0 id=table1>


<%
com.visualbuilder.beans.RegistrationBean
register=(com.visualbuilder.beans.RegistrationBean)session.getAttribute(bean);

String errors=(String)request.getAttribute(errors);
if(errors != null && errors.trim().length()>0){
out.println(<tr><td colspan='2'>The following are the errors with given
data<br>+errors+</td></tr>);
}
%>

<tr>
<td width=50%>Phone</td>
<td><input type=text name=phone size=20
value=<%=register.getPhone()!=null?register.getPhone():%>></td>
</tr>
<tr>
<td width=50%>Address</td>
<td><input type=text name=address size=20
value=<%=register.getAddress()!=null?register.getAddress():%>></td>
</tr>

126/148
Your First JSP Page 04/28/09 03:44:52

<tr>
<td width=50%>City</td>
<td><input type=text name=city size=20
value=<%=register.getCity()!=null?register.getCity():%>></td>
</tr>
<tr>
<td width=50%>State</td>
<td><input type=text name=state size=20
value=<%=register.getState()!=null?register.getState():%>></td>
</tr>
<tr>
<td width=50%>Country</td>
<td><select size=1 name=country>
<option selected value=United Kingdom>United Kingdom</option>
<option value=USA>USA</option>
<option value=other>Other</option>
</select></td>
</tr>
</table>
<p><input type=submit value=Submit name=B1><input type=reset value=Reset
name=B2></p>
</form>

</body>

</html>
Form:-

127/148
Your First JSP Page 04/28/09 03:44:52

Mutipage Forms-3

Mutipage Forms-3
This page is responsible for the validation. If validation fails it will again transfer the control to the first page with the
errors.

multipage3.jsp

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head>
<body>
<jsp:useBean id=bean class=com.visualbuilder.beans.RegistrationBean scope=session/>
<jsp:setProperty name=bean property=phone/>
<jsp:setProperty name=bean property=address/>
<jsp:setProperty name=bean property=city/>
<jsp:setProperty name=bean property=country/>
<jsp:setProperty name=bean property=state/>

<%
com.visualbuilder.beans.RegistrationBean
register=(com.visualbuilder.beans.RegistrationBean)session.getAttribute(bean);
register.validate(request);
String errors= (String)request.getAttribute(errors);
if( errors != null && errors.trim().length() >0){
%>
<jsp:forward page=multipage1.jsp></jsp:forward>
<%
}
%>
<h1>The given data is Valid.</h1>
</body>
</html>
Output:- The following page wil be displayed if any errors occured in the form.

128/148
Your First JSP Page 04/28/09 03:44:52

129/148
Your First JSP Page 04/28/09 03:44:52

Shopping Cart in JSP-1

Shopping Cart in JSP-1


Now we will be using all the concepts for the JSP learnt so far to implement in the shopping cart. We have a product page
where user select the product and add it to cart. Once user has product in the cart he can see the basket page to view the
products.

Example :-

ProductUtilities.java

ProductUtilities is the class which will have the hardcoded values for products and supplied the products for adding it to
basket and also to display the products to user for choice.

package com.visualbuilder.shopping;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ProductUtilities {

public static HashMap getProductsAsMap() {


HashMap<String, ProductBean> products= new HashMap<String, ProductBean>();
products.put(P1, new ProductBean(P1,Flower,10));
products.put(P2, new ProductBean(P2,Chair,200));
products.put(P3, new ProductBean(P3,Table,400));
products.put(P4, new ProductBean(P4,Microwave,400));
return products;
}
public static List getProductsAsList() {
List<ProductBean> products= new ArrayList<ProductBean>();
products.add(new ProductBean(P1,Flower,10));
products.add(new ProductBean(P2,Chair,200));
products.add( new ProductBean(P3,Table,400));
products.add( new ProductBean(P4,Microwave,400));
return products;
}

}
ProductBean.java

This is the actual bean for the product. All product has code, name, price and quantity as the properties.

package com.visualbuilder.shopping;

public class ProductBean {


String prodCode;

130/148
Your First JSP Page 04/28/09 03:44:52

String prodName;
double price;
int qty=1;
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public ProductBean(){
this.prodCode=;
this.prodName=;
}
public ProductBean(String code, String name, double price){
this.prodCode=code;
this.prodName=name;
this.price=price;
}
public String getProdCode() {
return prodCode;
}
public void setProdCode(String prodCode) {
this.prodCode = prodCode;
}
public String getProdName() {
return prodName;
}
public void setProdName(String prodName) {
this.prodName = prodName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}

131/148
Your First JSP Page 04/28/09 03:44:52

Shopping Cart in JSP-2

Shopping Cart in JSP-2


The below are the remaining code for the Basket.

Basket.java

package com.visualbuilder.shopping;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;

public class Basket {


HashMap<String, ProductBean> prodList =new HashMap<String, ProductBean>();
String selectedProducts;

public String getSelectedProdcuts() {


return selectedProducts;
}
public void setSelectedProducts(HttpServletRequest request) {
String[] ar = request.getParameterValues(selectedProducts);
if(ar != null && ar.length >0){
HashMap<String, ProductBean> map=
ProductUtilities.getProductsAsMap();
for(int i=0;i<ar.length;i++){
ProductBean bean =map.get(ar[i]);
if(bean != null){
ProductBean product= prodList.get(ar[i]);
if(product != null){
product.setQty(product.getQty()+1);
}else{
product=bean;
}
prodList.put(product.getProdCode(),product);
}
}
}
}

public HashMap<String, ProductBean> getProdList() {


return prodList;
}
public void setProdList(HashMap<String, ProductBean> prodList) {
this.prodList = prodList;
}
}
Productpage.jsp

132/148
Your First JSP Page 04/28/09 03:44:52

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<%@page import=com.visualbuilder.shopping.*,java.util.*; %>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head>
<body>
<form action=addtobasket.jsp method=post>
<table border=1 > <tr><th>Product Code</th><th>Product Name</th><th>Product
Price</th><th>&nbsp;</th></tr>
<% List<ProductBean> produList= ProductUtilities.getProductsAsList();
for (int i=0;i<produList.size();i++){
ProductBean bean = produList.get(i);
%>
<tr><td><%=bean.getProdCode() %></td><td><%=bean.getProdName()
%></td><td><%=bean.getPrice() %></td><td><input type=checkbox
name=selectedProducts value=<%=bean.getProdCode()%>></td></tr>
<%} %>
</table>
<input type=submit value=AddToCart>
</form>
</body>
</html>
Product Form:-

133/148
Your First JSP Page 04/28/09 03:44:52

Shopping Cart in JSP-3

Shopping Cart in JSP-3


The following is the code and form for addtocart page and basket page of the shopping cart.

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<%@page import=com.visualbuilder.shopping.*,java.util.*; %>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head>
<body>
<form action=addtobasket.jsp method=post>
<table> <tr><th>Product Code</th><th>Product Name</th><th>Product
Price</th><th>Quantity</th></tr>

<% Basket basket = (Basket)session.getAttribute(basket);


HashMap<String,ProductBean> prodList= basket.getProdList();
Iterator it=prodList.keySet().iterator();
double totalCost=0.0;
while(it.hasNext()){
ProductBean bean = prodList.get(it.next());
totalCost=totalCost+bean.getQty()*bean.getPrice();
%>
<tr><td><%=bean.getProdCode() %></td><td><%=bean.getProdName()
%></td><td><%=bean.getPrice() %></td><td><%=bean.getQty() %></td></tr>

<%} %>
<tr><td>&nbsp;</td><td>&nbsp;</td><td><b>Total</b></td><td><%=totalCost
%></td></tr>
</table>
<a href=productpage.jsp>Go to Product Page</a><br>
</form>
</body>
</html>
Form :-

134/148
Your First JSP Page 04/28/09 03:44:52

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<%@page import=com.visualbuilder.shopping.*,java.util.*; %>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head>
<body>

<jsp:useBean id=basket class=com.visualbuilder.shopping.Basket


scope=session></jsp:useBean>
<%
basket.setSelectedProducts(request);
%>
Products Added succesfully in Basket.<br>
<a href=productpage.jsp>Go to Product Page</a><br>
<a href=basketpage.jsp>Go to Basket</a><br>
</body>
</html>
Form :-

135/148
Your First JSP Page 04/28/09 03:44:52

JDBC and JSP

JDBC and JSP


This section will explain how do we can use the JDBC code in the JSP page. The below example will get the data from
the customer table of the database and display in the HTML table. The Customer table has only one row and has ID and
name as columns.

Example:-

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<%@page import=java.sql.*; %>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
<%
Connection con = null;
Statement stmt = null;
try{
Class.forName(com.mysql.jdbc.Driver);
con=DriverManager.getConnection(jdbc:mysql://localhost:3309/test,root,root);
stmt= con.createStatement();
ResultSet rs= stmt.executeQuery(select * from Customer);
out.println(Retreived Data is as follows:-<br>);
while (rs.next()){
out.println(ID is + rs.getInt(id)+<br>);

out.println(Name is + rs.getString(name)+<br>);
}
}catch(Exception e){
e.printStackTrace();
out.println(Exception Occured);
}finally{
if(con != null) con.close();
if(stmt != null) stmt.close();
}

%>

</body>
</html>
Output:- The following screen will be displayed when the file is run.

136/148
Your First JSP Page 04/28/09 03:44:52

137/148
Your First JSP Page 04/28/09 03:44:52

Data Sources in JSP

Data Sources in JSP


Traditional JDBC has the provision to register the driver classes before it is actually used. A driver that is accessed via a
DataSource object does not register itself with the DriverManager . Rather, a DataSource object is retrieved though a
lookup operation and then used to create a Connection object.

Being registered with a JNDI naming service gives a DataSource object two major advantages over the DriverManager .
First, an application does not need to hardcode driver information, as it does with the DriverManager . A programmer can
choose a logical name for the data source and register the logical name with a JNDI naming service.

Example:-

The following is the code of defining the datasource in the Tomcat server. We need to add the following resource in the
Tomcat's server.xml file.

<Context docBase=JSPExample path=/JSPExample reloadable=true


source=org.eclipse.jst.j2ee.server:JSPExample>
<Resource name=jdbc/TestDB auth=Container type=javax.sql.DataSource
maxActive=100 maxIdle=30 maxWait=10000
username=root password=root driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3309/test?autoReconnect=true/>
</Context>
The following code will bind the JNDI resource with the current application.

<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
The following code will use the data source and gets the data from the server.

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<%@page import=javax.naming.*,java.sql.*,javax.sql.*; %>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
<%
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup(java:/comp/env);
DataSource ds = (DataSource)envContext.lookup(jdbc/TestDB);
Connection con = null;

138/148
Your First JSP Page 04/28/09 03:44:52

Statement stmt = null;


try{
con = ds.getConnection();
stmt= con.createStatement();
ResultSet rs= stmt.executeQuery(select * from Customer);
out.println(Retreived Data is as follows:-<br>);
while (rs.next()){
out.println(ID is + rs.getInt(id)+<br>);

out.println(Name is + rs.getString(name)+<br>);
}
}catch(Exception e){
e.printStackTrace();
out.println(Exception Occured);
}finally{
if(con != null) con.close();
if(stmt != null) stmt.close();
}
%>
</body>
</html>
Output:- The following screen will be displayed when the above program is run.

139/148
Your First JSP Page 04/28/09 03:44:52

Data Source and Servlet

Data Source and Servlet


The following example will explain how do we use the datasource code inside the servlet. We will have a form where we
will have two fields one for id and another one for name. When user submit the form it invoke the database servlet which
will insert the values in the database table.

Example:-

JSP Form:-

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>

</head>
<body>
<form method=POST action=/JSPExample/insertData>

<table border=1 width=70% cellspacing=1 cellpadding=0 id=table1>


<tr>
<td width=50%>ID</td>
<td><input type=text name=id size=20></td>
</tr>
<tr>
<td width=50%>Name</td>
<td><input type=text name=name size=20></td>
</tr></table>
<p><input type=submit value=Submit name=B1><input type=reset value=Reset
name=B2></p>
</form>
</body></html>
Form:-

140/148
Your First JSP Page 04/28/09 03:44:52

141/148
Your First JSP Page 04/28/09 03:44:52

Data Source and Servlet Contd..

Data Source and Servlet Contd..


The servlet code and its entry in the web.xml is as follows:-

Example:-

Web.xml:-

<servlet>
<servlet-name>insertData</servlet-name>
<servlet-class>com.visualbuilder.servlet.InsertData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>insertData</servlet-name>
<url-pattern>/insertData</url-pattern>
</servlet-mapping>
Servlet Code:-

package com.visualbuilder.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

public class InsertData extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)throws
IOException,ServletException{
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws
IOException,ServletException{
String id=request.getParameter(id);
String name=request.getParameter(name);
Connection con = null;
Statement stmt = null;
try{
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup(java:/comp/env);
DataSource ds = (DataSource)envContext.lookup(jdbc/TestDB);
con = ds.getCnnection();

142/148
Your First JSP Page 04/28/09 03:44:52

stmt=con.createStatement();
stmt.executeUpdate(insert into customer values(+id+,'+name+'));
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(con != null) con.close();
if(stmt != null) stmt.close();
}catch(Exception e){}
}
response.sendRedirect(/JSPExample/database/datasourceexample.jsp);
}
}
Output:- When the data is entered it will be displayed on the page.

143/148
Your First JSP Page 04/28/09 03:44:52

Handling Transaction in JSP

Handling Transaction in JSP


Transactions in JSP is same as the transactions in JDBC. A transaction is defined as the one task which can be divided
into multiple tasks. The transactions can be controlled by setting the properties setAutoCommit(false) on connection
objects and then calling the rollback() or commit() methods as per the requirement. The below example is calling the
rollback() before commit() so there is no database update in the customer table and no new record gets inserted.

Example:-

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<%@page import=javax.naming.*,java.sql.*,javax.sql.*; %>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
<%
Context initContext = new InitialContext();
Contxt envContext = (Context)initContext.lookup(java:/comp/env);
DataSource ds = (DataSource)envContext.lookup(jdbc/TestDB);
Connction con = null;
Statement stmt = null;
try{
con = ds.getConnection();
con.setAutoCommit(false);
stmt= con.createStatement();
stmt.executeUpdate(insert into customer values(2,'transaction'));
con.rollback();
con.commit();
ResultSet rs= stmt.executeQuery(select * from Customer);
out.println(Retreived Data is as follows:-<br>);
while (rs.next()){
out.println(ID is + rs.getInt(id)+<br>);

out.println(Name is + rs.getString(name)+<br>);
}
}catch(Exception e){
e.printStackTrace();
out.println(Exception Occured);
}finally{
if(con != null) con.close();
if(stmt != null) stmt.close();
}
%>

144/148
Your First JSP Page 04/28/09 03:44:52

</body>
</html>
Output:-

145/148
Your First JSP Page 04/28/09 03:44:52

Calling Stored Procedure

Calling Stored Procedure


Stored procedures and functions helps to optimize the application which requires heavy database interaction. The
following section will explain how do we call the stored procedures stored in MySql database and gets the result in JSP.

Example:-

The following is the code for the procedure which will add 2 numbers num1 and num2 and return the result.

DELIMITER $$

DROP PROCEDURE IF EXISTS `test`.`TestProc` $$


CREATE DEFINER=`root`@`localhost` PROCEDURE `TestProc`(in num1 int,in num2
int, out result int)
BEGIN
Set result := num1+num2;
END $$

DELIMITER ;
The following is the code for the JSP page which will pass the values and get the out parameter from the procedure and
prints it on JSP page.

<%@ page language=java contentType=text/html; charset=ISO-8859-1


pageEncoding=ISO-8859-1%>
<%@page import=javax.naming.*,java.sql.*,javax.sql.*; %>
<!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN
http://www.w3.org/TR/html4/loose.dtd>
<html>
<head>
<meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1>
<title>Insert title here</title>
</head>
<body>
<%
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup(java:/comp/env);
DataSource ds = (DataSource)envContext.lookup(jdbc/TestDB);
Connection con = null;
CallableStatement stmt = null;
try{
con = ds.getConnection();
stmt= con.prepareCall(Call TestProc(?,?,?));
int result=0;
stmt.setInt(1,10);
stmt.setInt(2,5);
stmt.registerOutParameter(3,Types.INTEGER);
stmt.executeUpdate();
result = stmt.getInt(3);

146/148
Your First JSP Page 04/28/09 03:44:52

out.println(result);
}catch(Exception e){
e.printStackTrace();
out.println(Exception Occured);
}finally{
if(con != null) con.close();
if(stmt != null) stmt.close();
}
%>
</body>
</html>
Output:- The above program will print 15 on screen.

147/148
Your First JSP Page 04/28/09 03:44:52

Lifecycle of JSP

Lifecycle of JSP
When any request comes for the JSP the JSP engine checks whether the JSP is loaded in the memory or not. If it is not
then it brings the JSP page and compiled the JSP page. The JSP is then converted into the Servlet. The lifecycle of the JSP
also involved three methods like Servlets. The methods are as follows:-

• jspInit() :- This calls by the server when the JSP page is firstly loaded in the memory.
• jspService():- This method will be called for all the requests.
• jspDestroy():- This method will be called when the JSP's object is removed from the Server's memory.

The jspService method is container managed method and therefore it can not be overridden by any JSP page. But the other
two methods can be overridden in the JSP page. The jspInit() method mostly used to set the cache and resources for the
JSP page and jspDestroy() method is used to free the resources at the time the JSP page is offloaded or server is rebooted.
When we explain the database interaction then we will show how to override both methods.

Date entered : 13th Sep 2006


Rating :No Rating
Submitted by : visualbuilder

Copyright Visualbuilder.com 1999-2006


Document created date: 28 Apr 2009

148/148

You might also like