You are on page 1of 36

Easy JavaWeb

About The Author


I am Sivaramayya Madhupada, Sun Certified Professional. I have been working for
Miracle Software Systems since 2005 as a Sr.Technical Manager. Before coming to
work at Mracle, I worked for more than two years
as a C & J2EE faculty in CMC and Technical Head in
Logix Software Solutions. I used to give guest
lecturers in many institutions and engineering & PG
colleges. Basically, I spend a lot of my time helping
people be successful with the C & Java/J2EE coding.
This book is a reflection of what I do every day. The
book within covers topics and exercises that I see
people struggling with every day.
I spend the bulk of my time working with C, Java,
J2EE technologies,IBM tools like Webpshere Portals,
Websphere Commerce, Websphere Message
Broker, Rational Application Developer, Rational Software Architect, DB2 and etc.
Over the last 9 years, I have played many of the roles like Project Lead, Practice
Manager, Member of Center Of Excellence, Project Manager, and Currently as
Sr.Technical Manager. Ive worked on many domain (education, telecom, health
insurance, logistics and etc) projectssuccessful ones as well as complete failures. I
have worked with many resources. Some of them are lacking
fundamental
Programming skills, but I never find enough good time to spend with them. So I had
thought of starting this kind of book to give good fundamental programming
techniques in terms of education and industry approaches.
When I am doing my masters in computer science in Andhra Universitys College, I
used to take the classes and seminars in the class. When I am eagerly waiting for
sharing my knowledge and experience, Miracle Software Systems has started an
engineering college Miracle Educational society to produce world class
professionals. I have used this chance to convert my thoughts into physical form by
teaching C and Java.
Presently I am maintaining a website www.javasiva.in for technical education which
is helping many students related to computer science subjects. It is purely targeted
to B.Tech, MCA other computer science related students of all universities.
Many of IT students/Professionals reading my Easy C&DS,Easy Java, Easy JavaWeb
and Easy J2EE books. I am writing two more books with the below titles.
Easy Android
Easy Oracle

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 2 of 69

Easy JavaWeb

Target of This Book


This book is targeted to support the students and software engineers. I have written
this book to learn and understanding Webtechnologies using Java.It requires strong
knowledge on OOPS Concepts, Java Concepts and Application Development
Concepts.
There are many good books from good authors available in the market and they
have explained the things clearly. But there is no bridge between topics to topic to
go to the next level of reading. And to learn WebTechnologies using java, we need
to refer many books for some topics. They are throwing a lot of theory and less
appropriate scenarios/examples. It is completely time consuming process. This is
really irritating the student and developer communities.
Academic syllabuses are not allowing the students to meet the market requirement
properly. At the time of academics, it is somewhat difficult to prepare for industry;
because it is a separate path. Students are unable to concentrate on both academic
and industry paths simultaneously.
Industry professionals are missing their deadlines and unable to give good
productivity because of lacking of strong fundamental programming skills, and may
be lack of understanding the system.

Industries working experience in many projects with different roles,


Expertism on Java/J2EE technologies and IBM tools, working with many
different level of professionals, good track record in teaching experience
and working with many students from many colleges are given me an
alert that what is that the Professionals/Students are really looking for.
I have taken lot of care to align academic and industry paths into a single path to
meet requirements like how much content is sufficient for writing examinations
without having any confusion and what is that the industry is looking from students
or professionals.
I have designed this book for students and IT professional in such a way that they
can survive with this book to get good fundamental web programming skills.

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 3 of 69

Easy JavaWeb

Acknowledgment
One of the great pleasures of writing Easy JavaWeb and acknowledges the efforts
of many people whose names may not appear on the cover, but their hard work,
cooperation, friendship and understanding the situations are invested to complete
this book smoothly.
I would like to thank many people for helping me to complete this book. First; I
would like to convey my very special thanks to MCA/B.Tech students who have
encouraged me a lot. This book would not be there without them.
I would like to thank Srinivas Rao Bora (Senior Technical Associate, MSS) and
Chandrasekhar Kota (Team Lead, MSS) for their work making me to write Easy
JavaWeb. If you enjoy the flow of the sections, contents, and the clarity, then that
is probably in some part due to tehm. I have started writing this book since the year
2008.
I would like to thank to Mr.Prasad V Lokam, CEO, and MSS. When he is having free
time, he used to look at technical, project discussions and training. He used to tell
that dont throw much theory and learn by examples. I have started this book with
this motto only. I have learned many things from him like the way he is articulating
the things.
I am eager to convey my special thanks to Mr.Arjuna Rao A,Prinicipal,MES and
Ms.Madhavi Lokam,Chairman,MES and entire MES Team.I am very thankful to
Mr.Sankar Sastry Matta,Asst Professior,MES for his heartful support.
Last but not least, I would like to convey my heartfelt thanks to my family members
for their patience and bearing problems with me.

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 4 of 69

Easy JavaWeb

Preface
Industry working experience on different dominas using different java/J2EE
technologies, IBM tools and teaching of C and JAVA/J2EE motivated me to write this
book. It is targeted to support the students and software engineers.It will help you to
understand Advanced Java Programming concepts like HTML, CSS, JavaScritp, XML
AJAX, JDBC, Servlets, JSP, Custom Tags, and many advanced topics with
programmatic examples and pictorial explanations.
This book Easy JavaWeb addressed many problems and their solutions provided in
terms of algorithms and programming examples.This book contains scenarios which
are reflecting the real time scenarios. Students/Programmer/Developer tends to do
lots of mistakes while coding.This book providing Points to remember section to
alert the programmers not do any coding mistakes.This book contains many
exercises for each possible topic and you can see answers in next version.
You are having a good opportunity to learn advanced topics in java and J2EE
technologies by learning Easy Java, Easy JavaWeb and Easy J2EE books.
Now onwards, you will get more information from www.javasiva.in related to C&DS,
JAVA, Web technologies, DBMS and all universities B.Tech & MCA courses also. I am
expecting some important points from your side that are missing in this book like any
mistakes, readability problems and etc...Please write all your feedback to my email
and I will inject them to improve our book in all aspects. Thanks to all of my students
and Professors in advance for their support to write this book. The motto of this book
is to give good programming knowledge to meet industry requirements.
I have written some content which is somewhat simulated to many good sites and
their style of articulating the things were adapted. The definition of various software
engineering
terms
and
concepts
were
adapted
from
Wikipedia
(http://wikipedia.org/).
Prerequisites:Before start reading this book, please make sure that your system get
installed with JDK5.0/6.x, Netbeans5.5/6.x, Eclipse, and any application server like
GlassFish/Websphere
Application
server
and
any
database
like
IBMDB2/Oracle10g/MySQL. The most of the programs and concepts required JDK5.0
version.

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 5 of 69

Easy JavaWeb

Table of Contents
1.

HTML------------------------------------------------------------------------------------------ Error! Bookmark not defined.


1.1. Un Ordered List ------------------------------------------------------------------- Error! Bookmark not defined.
1.2. Ordered List ------------------------------------------------------------------------ Error! Bookmark not defined.
1.3. Definition List ---------------------------------------------------------------------- Error! Bookmark not defined.
1.4. Color and Image ------------------------------------------------------------------ Error! Bookmark not defined.
1.5. Linking ------------------------------------------------------------------------------ Error! Bookmark not defined.
1.6. Complex HTML Forms----------------------------------------------------------- Error! Bookmark not defined.
1.7. Tables ------------------------------------------------------------------------------- Error! Bookmark not defined.
1.8. Frames ------------------------------------------------------------------------------ Error! Bookmark not defined.

2.

CSS -------------------------------------------------------------------------------------------- Error! Bookmark not defined.


2.1. Types Of Styles ------------------------------------------------------------------- Error! Bookmark not defined.

3.

XML -------------------------------------------------------------------------------------------- Error! Bookmark not defined.


3.1. XML Validation -------------------------------------------------------------------- Error! Bookmark not defined.
3.2. XML Processing------------------------------------------------------------------- Error! Bookmark not defined.

4.

XHTML --------------------------------------------------------------------------------------- Error! Bookmark not defined.

5.

Javascript ---------------------------------------------------------------------------------- Error! Bookmark not defined.


5.1. Data Types & Variables --------------------------------------------------------- Error! Bookmark not defined.
5.2. Control Structures ---------------------------------------------------------------- Error! Bookmark not defined.
5.3. Arrays ------------------------------------------------------------------------------- Error! Bookmark not defined.
5.4. Functions --------------------------------------------------------------------------- Error! Bookmark not defined.
5.5. Windows Events ------------------------------------------------------------------ Error! Bookmark not defined.
5.6. String Handling -------------------------------------------------------------------- Error! Bookmark not defined.

6.

JDBC ------------------------------------------------------------------------------------------ Error! Bookmark not defined.


6.1. Loading The Driver ------------------------------------------------------------ Error! Bookmark not defined.
6.2. Getting a Connection With The Database ---------------------------- Error! Bookmark not defined.
6.3. Executing Statements -------------------------------------------------------- Error! Bookmark not defined.
6.4. JDBC Programs Using Netbeans------------------------------------------ Error! Bookmark not defined.
6.5. Getting Result ------------------------------------------------------------------- Error! Bookmark not defined.
6.6. Calling Procedures & Functions ----------------------------------------------- Error! Bookmark not defined.
6.7. Scrollable & Updatable ResultSets -------------------------------------- Error! Bookmark not defined.
6.8. Transactions --------------------------------------------------------------------- Error! Bookmark not defined.

7.

Servlets ------------------------------------------------------------------------------------- Error! Bookmark not defined.


7.1. CGI ---------------------------------------------------------------------------------- Error! Bookmark not defined.
7.2. Tomcat Server ------------------------------------------------------------------ Error! Bookmark not defined.
7.3. WebApplication ----------------------------------------------------------------- Error! Bookmark not defined.

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 6 of 69

Easy JavaWeb
7.4. Deployment of Webapplication ------------------------------------------------ Error! Bookmark not defined.
7.5. Servlet Life Cycle -------------------------------------------------------------- Error! Bookmark not defined.
7.6. Servlet API ----------------------------------------------------------------------- Error! Bookmark not defined.
7.7. Servlet Artchitecture---------------------------------------------------------- Error! Bookmark not defined.
7.8. Request Processing ----------------------------------------------------------- Error! Bookmark not defined.
7.9. Creating a Servlet ------------------------------------------------------------- Error! Bookmark not defined.

8.

7.10.

Creating Application Using NetBeans------------------------------- Error! Bookmark not defined.

7.11.

Reading Data From HTML Form -------------------------------------- Error! Bookmark not defined.

7.12.

Session Tracking/State Programming------------------------------ Error! Bookmark not defined.

7.13.

HttpSession ------------------------------------------------------------------ Error! Bookmark not defined.

7.14.

Cookie -------------------------------------------------------------------------- Error! Bookmark not defined.

7.15.

ServletConfig ---------------------------------------------------------------- Error! Bookmark not defined.

7.16.

ServletContext -------------------------------------------------------------- Error! Bookmark not defined.

7.17.

Inter Servlet Communication/ Collaboration -------------------- Error! Bookmark not defined.


7.17.1. redirect vs forward ------------------------------------------------ Error! Bookmark not defined.

7.18.

E-Commerce Project ------------------------------------------------------ Error! Bookmark not defined.


7.18.1. Setting a Default page for an Application ---------------- Error! Bookmark not defined.

7.19.

Change Salary Project --------------------------------------------------- Error! Bookmark not defined.

7.20.

File Uploading --------------------------------------------------------------- Error! Bookmark not defined.

7.21.

Filters --------------------------------------------------------------------------- Error! Bookmark not defined.

7.22.

Listeners----------------------------------------------------------------------- Error! Bookmark not defined.

7.23.

Servlet Security Issues -------------------------------------------------- Error! Bookmark not defined.

JSP -------------------------------------------------------------------------------------------------------------------------------- 9
8.1. JSP Phases and Life Cycle -------------------------------------------------------------------------------------- 10
8.2. Anatomy/Structure of a JSP Page --------------------------------------------------------------------------- 11
8.3. JSP Elements -------------------------------------------------------------------------------------------------------- 12
8.4. Implicit Obects ------------------------------------------------------------------------------------------------------ 14
8.5. Creating Webapplication using Eclipse--------------------------------------------------------------------- 15
8.6. Exception Handling ------------------------------------------------------------------------------------------------ 23
8.7. Session Tracking/State Programming---------------------------------------------------------------------- 24
8.8. HttpSession/session ---------------------------------------------------------------------------------------------- 27
8.9. Cookie ------------------------------------------------------------------------------------------------------------------ 29

9.

8.10.

Includes and Forwards --------------------------------------------------------------------------------------- 31

8.11.

JavaBeans -------------------------------------------------------------------------------------------------------- 33

8.12.

Accessing Database from JSP ----------------------------------------------------------------------------- 36

8.13.

E-Commerce Project ------------------------------------------------------------------------------------------ 37

8.14.

Users Info From XML ----------------------------------------------------------------------------------------- 45

8.15.

Memory Usage Considerations---------------------------------------------------------------------------- 48

8.16.

JSP Application Using MVC --------------------------------------------------------------------------------- 49

Custom Tags ----------------------------------------------------------------------------------------------------------------- 53

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 7 of 69

Easy JavaWeb
9.1. Tag Life Cycle ------------------------------------------------------------------------------------------------------- 53
9.2. Tag with attributes ------------------------------------------------------------------------------------------------ 56
9.3. Tags With Body ----------------------------------------------------------------------------------------------------- 58
9.4. Tags With Iterations ---------------------------------------------------------------------------------------------- 60
10. AJAX ---------------------------------------------------------------------------------------------------------------------------- 62
10.1.

XMLHttpRequest------------------------------------------------------------------------------------------------ 62

10.2.

Working With Text--------------------------------------------------------------------------------------------- 64

10.3.

Working With XML --------------------------------------------------------------------------------------------- 66

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 8 of 69

Easy JavaWeb
1.

JSP
Java server pages is the J2EE technology for generating dynamic web content.A JSP page is a textbased document that contains two types of text:
static template data: which can be expressed in any text-based format, such as
HTML,SVG, WML, and XML and will be used for presentation.
JSP elements: which construct dynamic content based on the logic.
JSP provides clear separation between logic and presentation. JSP simply puts Java code inside HTML
pages and saving the file with .jsp extension.
Disadvantages with Servlets: When we are developing servlets,we need to have many things in
to consideration like overriding service methods and entries in web.xml. From the developers
perspective Servlets are pure java programs with class and method definitions whereas a JSP page is
much like a text document or web page. With servlets developer must write java code to output the
entire markup, on the other hand a JSP page can be designed like a static web page. JSP separates
static content from dynamic content.Servlets are well suited for handling client request and
executing application logic whereas JSP pages are well suited as views and application logice also.
I am listing out the some of disandvantages.

Thorough Java programming knowledge is needed to develop and maintain all aspects of the
application, since the processing code and the HTML elements are dumped together.

Changing the look and feel of the application, or adding support for a new type of client (such
as a WML client), requires the servlet code to be updated and recompiled.

It's hard to take advantage of web-page development tools when designing the application
interface. If such tools are used to develop the web page layout, the generated HTML must
embedded into the servlet code manually, which is time consuming, error prone, and
extremely boring.

Aim of JSP: Separation of request processing, business logic, and presentation.And also providing
below benefits.

Auto transition and compilation.Means we need not recompile every time when we do
changes in JSP.

There is no deployment descritpor for JSP.

Multiple deployment is avoided.Means on the fly we can do changes to JSP Pages.

JSP are translated and compiled into JAVA servlets but are easier to develop than JAVA
servlets.

JSP uses simplified scripting language based syntax for embedding HTML into JSP.

JSP containers provide easy way for accessing standard objects and actions.

JSP reaps all the benefits provided by JAVA servlets and web container environment, but
they have an added advantage of being simpler and more natural program for web
enabling enterprise developer

JSP use HTTP as default request /response communication paradigm and thus make JSP
ideal as Web Enabling Technology.

We can observe that how JSP coding simplifying the servelt code.

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 9 of 69

Easy JavaWeb
Helloworld Servlet

Helloworld JSPPage

import javax.servlet.*;
public class HelloWorldServlet implements
servelet{
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException {
response.setContentType(text/html);
PrintWriter out=response.getWriter();
out.println(<html>);
out.println(<head>);
out.println ( <title>Hello world</title>);
out.println(</head>);
out.println(<body>);
out.println(<h1>Hello World<\h1>All is well);
out.println(</body>);
out.println(</html>);
}
}

<html>
<head>
<title>Hello world <\title>
</head>
<body>
<h1>Hello World<\h1>
All is well.
</body>

</html>

1.1. JSP Phases and Life Cycle


Ever JSP page will be converted into a servlet.Here is the process of JSP.

Whenever a .jsp is requested for the first time, the server does the following phases:
Life cycle of a JSP page consists of three phases, translation phase, compilation phase and
execution phase. As I said earlier that every JSP is a Servlet, a JSP page is translated and
compiled into servlet and the resulting servlet handles the request, So life cycle of a JSP
page cmpletely depends on the Servlet API.

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 10 of 69

Easy JavaWeb
Translation Phase: Here the webcontainer will translates the .jsp page into a servlet
compatable java file.Here the entire static markup in the JSP page is converted into
the code that writes the data to response stream. If you look at the source of the
generated Servlet class you will find calls to the out.write() which write data to
ServletOutputStream.
If you have following HTML code into your JSP page
<h1>Hello World<\h1>
It will generate code like out.write(<h1>Hello World<\h1>)
During the translation phase JSP elements are treated as follows:
o

JSP directives controls the behavior of the resultant servlet.

Scripting elements results into the equivalent Java code.

Custom tags are converted into the code that calls method on tag handlers.

Compilation Phase: Here servlet compatible java file will be compiled into a class
file.
Execution Phase: Executes the servlet (response is sent to the client). JSP life cycle's
execution phase is almost similar to that of the Servlet life cycle, because ultimately
it's a servlet which is being executed. The Servlet class generated at the end of the
translation phase represents the contract between container and the JSP page.
According to the JSP specification the servlet class must implement the HttpJspPage
interface which defines the life cycle methods.
JSP life cycle includes three methods jspInit(), _jspService() and jspDestroy()
a.

jspInit():This method is invoked when the JSP page is initialized. This method is
similar to init() method in servlet. If you want to provide initialization for a JSP page,
you define this method in declaration part of the JSP page. But most of the time you
will not need to define this method.

b.

_jspService:This method represents the body of the JSP page and invoked at each
client request. This method is similar to service() method in servlet.
Note: You should never provide implementation _jspService() method as web
container automatically generates this method based on the content of the JSP page

c.

jspDestroy():This method is called only once in JSP's servlet life time, when the JSP
Engine removes the JSP's servlet from memory. It is always better to remove
instance variable resources such as JDBC connections, sockets, other physical
resources in this method to avoid memory leaks.

Note:Please refer Classes and Objects topic in EasyJava book for getting information on
instantiation and initialization.
1.2.

Anatomy/Structure of a JSP Page


A JSP page is a mixture of standard HTML tags, web page content, and some dynamic
content that is specified using JSP Elements and implicit objects. Everything except the JSP
constructs is called Template Text which can be text or HTML. Everything in the page that
isn't a JSP element is called template text. Template text can be any text: HTML, WML,
XML, or even plain text.
<HTML>
<HEAD>
<TITLE>JSP Color Program</TITLE>
</HEAD>
<% String bgColor = request.getParameter("COLOR"); %>
JSP Elements
<% if (bgColor == null) { %>

Template Text
Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 11 of 69

Easy JavaWeb
<BODY BGCOLOR="FFFFFF" >
<% } else { %>
<BODY BGCOLOR="<%= bgColor %>" >
<% } %>

Mixture of JSP Elements and


Tempate text

</BODY>
</HTML>
When a JSP page request is processed, the template text and dynamic content generated by
the JSP elements are merged, and the result is sent as the response to the browser.
1.3.

JSP Elements
There are six types of JSP elements that you can use and they are:
1.

Declaration Element: A JSP element provides the capability of inserting Java


declaration statements into the Servlet class. Here is the syntax for the declaration
element.
<%! Java decalaration statements %>

2.

Scriptlet Element: A JSP element provides the capability of embedding Java


expressions to be evaluated as part of the service method of the Servlet class. An
scripting element can be written in two ways:
<% Java statements %>

3.

Expression Element: A JSP element provides the capability of embedding Java


expressions to be evaluated as part of the service method of the Servlet class. An
expression element can be written in two ways:
<% Java expressoins %>

4.

Comments Element:This elements helps the developer to write documentation of the


statements for better understanding of the program.Below is the syntax:
<%-- description of process --%>

5.

Directive elements:These will be considered at the time of translation.The directive


elements, shown in Table, specify information about the page itself that remains the
same between requests.For example, if session tracking is required or not, buffering
requirements, and the name of a page that should be used to report errors, if any.
Directive elements

Description

<%@ page ... %>

Defines page-dependent attributes, such as session


tracking, error page, and buffering requirements
Includes a file during the translation phase
Declares a tag library, containing custom actions, that
is used in the page

<%@include ... %>


<%@ taglib ... %>

Among all directives, page directive will play major role. So Now I am giving information
about page directive and sub sequent topic will address remaining two directives.
Page directive:Page directive are having these attributes and here I am listing out the
some of important attributes
import :Import is used to import java classes and package methods.This translates
JSP engine to include classes in JSP servlet. Comma is used to separation between
classes and package.
<%@page import="java.sql.*,java.text.SimpleDateForamt"%>
errorPage: errorPage=relativeURL. When an exception is occur in JSP, errorPage
transfer the control of page to defined URL which is set in errorPage. This is
customized presentation of errors to user. If relativeURL found blank, exception will
throw on same page.
Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 12 of 69

Easy JavaWeb
<%@ page errorPage="error.jsp" %>
isErrorPage: isErrorPage=false | true . isErrorPage in JSP translate JSP engine to
display exception or not. If set false, we can not use exception objects in JSP page.
Default value is true.
<%@ page isErrorPage="true" %>
isThreadSafe: isThreadSafe="true | false" .This attribute translate as JSP class is
thread safe or not. In multiple threads, concurrent number of users can request to
JSP page. JSP process this request, this results in using variable, code at a same
time. We can synchronize request to JSP with this attribute. If isThreadSafe is false,
one request process to JSP at same time, and implement as SingleThreadModel. We
suggest to use isThreadSafe in rare cases when really need it.
<%@ page isThreadSafe="true" %>
Buffer: buffer="none | 8k | size" .buffer in page directive specify the buffer size of
out object to print on client browser. Default size of buffer is 8k, can change to as
requirement.
<%@ page buffer="16kb" %>
autoFlush: autoFlush=true | false .when buffer get full it is automatically flush, if it
is set as true. In false case, it throws exception of overflow.
<%@ page autoFlush="true" %>
session: session=true | false. Session attribute in page translate to JSP engine to
use session object in current JSP page. If session attribute set as false in page
directive we can not use session in current JSP.By default it is true.
<%@ page session="true" %>
extends: extends=class.package.ClassName .extends is used to override the class
hierarchy provided by JSP container. It is something like to deploy own our classes
instead of using JSP container classes. It should be used with precaution unless you
know it clearly. It is used when we need tag libraries.
<%@ page extends="com.myapp.ClassName" %>
6.

action elements: These will be considered at the time of execution.Means action


elements typically perform some action based on information that is required at the time
of JSP page is requested by a browser. JSP actions use constructs in XML syntax to
control the behavior of the servlet engine. You can dynamically insert a file, reuse
JavaBeans components, forward the user to another page, or generate HTML for the
Java plugin.
Syntax for the Action element, as it conforms to the XML standard:

<jsp:action_name attribute="value" />

Action elements are basically predefined functions and Here is the list of common JSP
actions:
Actions
jsp:include

Purpose
Includes a file at the time the page is requested

jsp:useBean

Finds or instantiates a JavaBean

jsp:setProperty

Sets the property of a JavaBean

jsp:getProperty

Inserts the property of a JavaBean into the output

jsp:plugin

Forwards the requester to a new page


For executing applets

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 13 of 69

Easy JavaWeb
jsp:param
1.4.

For sending pararmeters through request object.

Implicit Obects
Implicit objects in jsp are the objects that are created by the container automatically and
makes them available to the JSP.Developers do not need to create them explicitly. Since
these objects are created automatically by the container and are accessed using standard
variables; hence, they are called implicit objects. The implicit objects are parsed by the
container and inserted into the generated servlet code. There are nine implicit objects. Here
is the list of all the implicit objects:
1.

out: is instance of javax.servlet.jsp.JspWriter class and that can be used to write to


the response to the client.
<%
out.write("This is used for printing output on client");
%>

2.

page: It is representation of java.lang.Object class and is an instance of the JSP


page's servlet class that processes the current request. Page object represents the
current page that is used to call the methods defined by the translated servlet class.
<%
Object page = this;
%>

3.

pageContext:pageContext instance contains information, which is associated with


JSP page. This helps to access attribute and other fields object set in JSP page.
pageContext is instance of javax.servlet.jsp.PageContext class. pageContext is to
managed various scope of attribute in shared information object.This object will be
useful in custom tag development.Method of pageContext are following:
pageContext.getException() returns Exception
pageContext.getOut() returns JspWriter
pageContext.getRequest() returns ServletRequest
pageContext.getResponse() returns ServletResponse
pageContext.getServletConfig() returns ServletConfig
pageContext.getServletContext() returns ServletContext.
pageContext.getSession() returns HttpSession.

4.

request: It is representation of javax.servlet.http.HttpServletRequest class is


provided to access request objects in JSP. The HTTP request is send to server
through request object.

5.

response: It is an representation of javax.servlet.http.HttpServletResponse class is


provided to send response object in JSP. The HTTP response is send to client
through response object .

6.

session: It is an representation of javax.servlet.http.HttpSession and session


object is used to track information about a user.

7.

config: It is an representation of javax.servlet.ServletConfig class. Config object


allows to pass the initialization data to a JSP page's servlet. Parameters of this
objects can be set in the deployment descriptor (web.xml) inside the element <jspfile>.
Method use to get init param is getInitParameter() to get value inside <paramvalue> and getInitParameterNames() to get name of <param-name>

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 14 of 69

Easy JavaWeb
8.

application:It is used to share information for all JSPs and Servlets in the
application context. application is instance of javax.servlet.ServletContext.

9.

exception: It is an instance of java.lang.Throwable class. This object allows the


exception data to be accessed only by designated JSP "error pages".

The scope constrains the accessibility and lifetime of the object and these details are
summarized in below table.This table will be help us in coming examples.

1.5.

Name

Accessible From

Lifetime

page

Current page

request

Current page and any included


or forwarded pages

session

Current request and any


subsequent request from the
same browser.

The life of the user's session

application

Current and any future request


from the same Web application

The life of the application

Until the response has been sent back


to the user or the request is passed to
a new page
Until the response has been sent back
to the user

Creating Webapplication using Eclipse


Already we have seen that how to develop a webapplication using Netbeans in then earlier
chapter. Working with JSP is also same, but instead of selecting Servlet we will select JSP.
Now I want to let you know how to work with Eclipse in this chapter.So that you will have
more exposure.

Note: We should remember strongly that IDEs does not do any thing and
they are just for helping us many ways to speed up the development and
deployment processes.
Step1: whenever we launch Eclipse then it will ask us for location of workspace where all of
our projects will stroed.

Click Ok. Then we will get the below screen.

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 15 of 69

Easy JavaWeb

Step2: Now its the time to create the server to deploy our applications. In the Servers view
is a view that contains nothing. This view is for application and Web servers; it let us to
control them and monitor their status. Right Click New Server from the contextsensitive menu. The New Server wizard, as shown in below Figure.

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 16 of 69

Easy JavaWeb
Click next and then give the base location of tomcat server like below.

Click Finish.
Step3:Next, create a simple Web application likw File New select Dynamic Web Project
and then you will get the below window

Enter a name for the project and note that the Target runtime field is pre-populated with the
servers which we created earlier.So select one of them from this list. Accept the default
values for all the fields in this dialog and click Finish.
Step4:Now you will create a JSP page within your new project. Expand the project you
created and then the WebContent folder.Right-click on the WebContent folder and select the
New JSP menu and then screen will be like below.
Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 17 of 69

Easy JavaWeb

Enter a name for the file, such as HelloWorld, and click Finish.
Step5:The file is opened in a JSP Editor. Enter the below code
<% out.print("Hello World!!"); %>
Save the file.
Step6:Deploying our Web Application by Right-click on the JSP file, HelloWorld.jsp, in the
ProjectExplorer. Select Run As > Run on Server menu and we can see this in below figure.

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 18 of 69

Easy JavaWeb
In the Run On Server dialog box, verify that the server Tomcat V5.5 Server is selected like
below.

Click Finish. The Eclipse will now do the following:


Package the Web application.
Start the Tomcat server if it is not running.
Publish the application to the Tomcat instance.
The console view displays the log tracking and the progress of the deployment.
Launch the application in a browser like below.

Now we will look at the some of basic examples.


Example1:Put the following text in a file with .jsp extension (let us call it hello.jsp), place it in
your
application
(let
us
call
it
World),
and
view
it
in
a
browser
like
http://localhost:8075/World/hello.jsp.

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 19 of 69

Easy JavaWeb
<HTML>
<BODY>
Hello! The time is now <%= new java.util.Date() %>
</BODY>
</HTML>
Output:

Observe that each time you reload the page in the browser, it comes up with the current
time.The element <%= and %> enclose Java expressions, which are evaluated at run time.
This is what makes it possible to use JSP to generate dyamic HTML pages.

Example2:Demonstration of using JSP scriptlets, expressions, comments(JSP & HTML)


<!-- Html Comments will be sent to the client. -->
<%-- SP Comments will not be sent to the client. --%>
<%
for (int i = 1; i <= 10; i++) {
out.print(i + "<br>");
AAAAAA
}
%>
<TABLE BORDER=1>
<%
for (int i = 1; i <= 10; i++) {
%>
<TR>
<TD>Number:</TD>
<TD><%= i%></TD>
</TR>
<%
}
%>
</TABLE>

Output:

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 20 of 69

Easy JavaWeb

Observation: We can see how to use the "out" variable to generate HTML output from within a
scriptlet in section A. For more complicated HTML, using the out variable all the time loses some of
the advantages of JSP programming. It is simpler to mix java and HTM using expressions like section
B.
Example3:Demonstration of using JSP declaration,scriptlets and expressions.
<%! int i = 10;
int j = 10;
public int getSum() {
return i + j;
}
%>
<%="Sum=" + getSum()%><br>
<%
out.println("Sum=" + getSum());
%>
Output:

Example4:Demonstration of using page directive.


<%@ page import="java.util.*" %>
<BODY>
Hello! The time is now <%= new Date()%>
</BODY>
Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 21 of 69

Easy JavaWeb
Output:

Example4:Demonstration of submitting a form to JSP page which reads the data.


<html>
<head>
<title>Input Details</title>
<script>
function ValidateData()
{
//alert("helo");
var bol=true;
if(document.f1.usr.value=="")
{
alert("enter USERNAME");
return false;
}
if(document.f1.pwd.value=="")
{
alert("enter password");
return false;
}
}
function go()
{
f1.submit();
}
function checkNumeric(text)
{
var ValidChars = "0123456789-.";
var IsNumber=true;
var Char;
var x=text.value;
for (i = 0; i < x.length && IsNumber == true; i++)
{
Char = x.charAt(i);
if (ValidChars.indexOf(Char) == -1 || x.charAt(0) == "." ||x.charAt(0) == " ")
{
IsNumber = false;
alert("Please Enter a valid Number");
x.select();
x.focus();
}
}
return IsNumber;
}
</script>
Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 22 of 69

Easy JavaWeb
</head>
<body>
<form name="f1" action="/JSPBasics/take.jsp" method="get">
username<input name="usr" ><br>
pasword<input type="password" name="pwd"><br>
Age:<input type="text">
<input type="submit" value="SubGo" >
<input type="button" value="ButGo" >
</form>
</body>
</html>

take.jsp
<%
String us = request.getParameter("usr");
String pw = request.getParameter("pwd");
out.println("<font color=green size=45>usr: " + us + "<br>");
out.print("pswd: " + pw);
%>

1.6. Exception Handling


The exception implicit object is of type java.lang.Throwable class and this object is only
available to pages that have isErrorPage set to true with the directive.
<%@ page isErrorPage='true' %>

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 23 of 69

Easy JavaWeb
The exception object refers to the exception triggered by the page that uses this page as an
exception handler.
The following code demonstrates the use of the exception implicit object. The first page uses
the errorPage directive to set up the JSP page to use when an exception occurs, and the second
page called ErrorPage.jsp uses the isErrorPage directive to set itself up to catch the exception.
parsing.jsp
<%@ page errorPage = "error.jsp" %>
<%
int i=Integer.parseInt("23a");
out.print(i);
%>
error.jsp
<%@ page isErrorPage="true" %>
<html>
<head>
<title>Implicit Exception Error page</title>
</head>
<body>
The Exception is <strong><%= exception.toString() %></strong><br>
Message : <strong><%=exception.getMessage()%></strong><br>
</body>
</html>
Declarative handling of exceptions: It is also possible to map HTTP error codes and or Java
exception types to an error page in the deployment descriptor. This is done at the web
application level by using the <error-page> tag which is a child of the <web-app> tag.
The following tags would redirect all SQL exception errors to the /errorpage.jsp page.
<error-page>
<exception-type>java.sql.SQLException</exception-type>
<location>/errorpage.jsp</location>
</error-page>
The following tags would redirect all HTTP 404 errors to the /errorpage.jsp page
<error-page>
<error-code>404</error-code>
<location>/errorPage.jsp</location>
</error-page>
1.7.

Session Tracking/State Programming


For Example, when you are doing on-line shopping, it is a real irritation that the Web server
can't easily remember previous transactions. This makes applications like shopping carts
very problematic: when you add an entry to your cart, how does the server know what's
already in your cart? When you move from the page where you specify what you want to
buy to the page that takes your credit card number and shipping address, how does the
server remember what you were buying?
The above questions are there because it is really a fact that HTTP is stateless protocol and it
does not maintain the client state.Means once the server sends the response back to the
client, that connection will be disconnected.But there exist a mechanism called "Session
Tracking" which helps the servers to maintain the state to track the series of requests from
the same user across some period of time.
Session Tracking Mechanisms:

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 24 of 69

Easy JavaWeb
1.

URL Rewriting:You can append some extra data on the end of each URL that
identifies the session. This is also an excellent solution,when browsers that don't
support cookies or where the user has disabled cookies. You need to use ? and name
and value separated by =.If we have more pairs then use & like below:
http://localhost:8080/rewriting/next.jsp?par=AJP
Data.html
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h1>Login Form</h1>
<form method = "post" action = "/JSPBasics/query/take.jsp">
Enter your name : <input type = text name =txtName><br>
<input type = submit name = submit value = submit >
</form>
</body>
</html>

take.jsp
<a href=/JSPBasics/query/next.jsp?par=<%=request.getParameter("txtName")%> >
next</a>

next.jsp
Welcome to: <%= request.getParameter("par")%>

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 25 of 69

Easy JavaWeb

2.

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.Usage of
hidden field will be like below:
<input type=hidden name=par value=AJP>
Data.html
<html>
<head><title>Login Form</title></head>
<body>
<h1>Login Form</h1>
<form method = "post" action = "/JSPBasics/hidden/take.jsp">
Enter your name : <input type = text name =txtName><br>
<input type = submit name = submit value = submit >
</form>
</body>
</html>

take.jsp:hidden will never comes on the screen.


<form action=/JSPBasics/hidden/next.jsp>
<input type=hidden name=par value="<%=request.getParameter("txtName")%>">
<input type=submit value=Next>
</form>

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 26 of 69

Easy JavaWeb
next.jsp:
out.print(Welcome to: +request.getParameter("par"));

1.8.

3.

HttpSession: Servlets provide an outstanding technical solution that is HttpSession


API. This is a high-level interface built on top of cookies or URL-rewriting. In fact, on
many servers, they use cookies if the browser supports them, but automatically revert
to URL-rewriting when cookies are unsupported or explicitly disabled. But the servlet
author doesn't need to bother with many of the details, doesn't have to explicitly
manipulate cookies or information appended to the URL, and is automatically given a
convenient place to store data that is associated with each session. we will discuss it
in later section in detail.

4.

Cookies: Cookie a small data file reside in users system. Cookie is made by web
server to identify users. When user do any request send to web server and web server
know information of user by these cookie. After process request, web server response
back to request through this cookie. javax.servlet.http.Cookie, by this classes we can
create and retrieve cookie. Once we set value in cookie, it lived until cookie gets
expired. Cookie plays a big role in session, because maximum session is tracked by
cookie in Servlets.we will discuss it in later section in detail.

HttpSession/session
Session object is medium to interact with client and server. Session is a connection between
user and server, involving exchange of information between users computer and server.
Server knows information about each other by these session object. Web server put
information of user in session object and whenever it needs information gets it from these
session objects. This session object stores information in key value pair, just like hashtable.
Today programming without session cannot be thinkable. Most of web application is user
based, somewhat use transaction (credit card, database transaction), shopping cart, email,
and this needs session. Web server should know who is doing this transaction. This session
object helps to differentiate users with each other, and increase applications security. Every
user have unique session, server exchange information with session objects until it get
expired or destroyed by web server.
When to use Session:Mostly session is work with user base application, when login
screen is used then set session if login is successful. It set for maximum time
provided by web.xml or defined by application.
When to destroy Session:When user has done their work and want to close
browser, it should be expire or destroy forcefully by user, ensure no other person
can use his session.
Usage of Session:To get HttpSession obect, we need to call getSession() on
request obect like below:
HttpSession session = request.getSession(true);
Def between getSession(true) /getSession() and getSession(false):Both
request.getSession() and request.getSession(true) are same.They will return the
current session and if one does not exist, a new session will be cretaed.

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 27 of 69

Easy JavaWeb
If we use request.getSession(false), it will return the current session if one exists
and if one DOES NOT exist, a new one will NOT be cretaed.
session.setAttribute("name",value) is use to set new session variable. If we need to
retrieve session variable, have to use session.getAttribute(name). In this we have
to get it by session variable name here we are using name is session variable as
key.New session can be find by isNew() method of session, when first time session
is created, that is new session.
Inactivate Session Automatically:To inactivate session at runtime, use
session.setMaxInactiveInterval(2700), this will set maximum session time. 2700 is
time in number. In this period, if user dont do anything session get expired
automatically.we can also specify the session period in web.xml like below:
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
Expire Session Forcefully or Remove All Session Variables:When session is no
long needed, should be removed forcefully by user. This can be done by calling
session method of invalidate method session.invalidate(); This method expires
session for current user, who request for log out.
Example3:Demonstration of using session object for marriage details.
bride.html
<form name="f1" method="get" action="/Marriage/ses1.jsp">
<table border=1>
<tr><td>Bride</td><td><input type=text name="txtBride" value="" ></td></tr>
<tr><td colspan=2 align=center><input type="submit" name="sub"
value="Go"></td></tr>
</table>
</form>
ses1.jsp
<%
String st=request.getParameter("txtBride");
session.setAttribute("bride",st);
%>
<form name="f1" method="get" action="/Marriage/ses2.jsp">
<table border=1>
<tr><td>BrideGrome</td><td><input type=text name="txtBG" value="" ></td></tr>
<tr><td colspan=2 align=center><input type="submit" name="sub"
value="Go"></td></tr>
</table>
</form>
ses2.jsp
<%
session.setAttribute("BG",request.getParameter("txtBG"));
%>
<center>
<form name="f1" method="get" action="/Marriage/ses3.jsp">
<table border=1>
<tr><td>BrideAge</td><td><input type=text name="Bage" value="" ></td></tr>
<tr><td>Groom Age</td><td><input type=txt name="BGage" value=""></td></tr>
<tr><td colspan=2 align=center><input type="submit" name="sub"
value="Go"></td></tr>
</table>
</form>

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 28 of 69

Easy JavaWeb
ses3.jsp
<table border="1" align="center">
<thead>
<tr><th>Marriage</th><th>Name</th><th>Age</th></tr>
</thead>
<tbody>
<tr>
<td>Bride</td>
<td><%=session.getAttribute("bride")%></td>
<td><%=request.getParameter("Bage")%></td>
</tr>
<tr>
<td>BrideGroom</td>
<td><%=session.getAttribute("BG")%></td>
<td><%=request.getParameter("BGage")%></td>
</tr>
</tbody>
</table>
Output of the above application like below:

1.9.

Cookie
Cookie a small data file reside in users system. Cookie is made by web server to identify
users. When user do any request send to web server and web server know information of
user by these cookie. After process request, web server response back to request by
knowing through this cookie. JSP provides cookie classes, javax.servlet.http.Cookie, by this
classes we can create and retrieve cookie. Once we set value in cookie, it lived until cookie
gets expired. Cookie plays a big role in session, because maximum session is tracked by
cookie in Servlets.
creating Cookie: Cookie cookie = new Cookie ("key",value);
Then we are adding in cookie of response object like:response.addCookie(cookie);
Expire cookie:To destroy the cookie we need to create the cookie with the same
name and we need to their maximum age like below:
Cookie cookie = new Cookie ("cookieSet",cookieSet);
cookie setMaxAge(0);
This will expire cookie.,with 0 second.
Retrieve cookie:Cookie is in array object, we need to get in request.getCookies()
of array like below:
Cookie[] cookies = request.getCookies();
for (int i=0; i<cookies.length; i++) {
out.println(cookies[i].getName()+" : "+cookies[i].getValue()+"<br/>");

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 29 of 69

Easy JavaWeb
}
Example4:Demonstration of using Cookies for marriage details.
bride.html
<form name="f1" method="get" action="http://localhost:8084/cooki/cook1.jsp">
<table border="1" >
<tr><td>Bride</td><td><input type=text name="txtBride" value="" ></td></tr>
<tr><td colspan=2 align=center><input type="submit" name="sub"
value="Go"></td></tr>
</table>
</form>
cook1.jsp
<%
String st=request.getParameter("txtBride");
Cookie c1=new Cookie("bride",st);
response.addCookie(c1);
%>
<form name="f1" method="get" action="http://localhost:8084/cooki/cook2.jsp">
<table border="1" >
<tr><td>BrideGrome</td><td><input type=text name="txtBG" value="" ></td></tr>
<tr><td colspan=2 align=center><input type="submit" name="sub"
value="Go"></td></tr>
</table>
</form>
cook2.jsp
<form name="f1" method="get" action="http://localhost:8084/cooki/cook3.jsp">
<table border=1>
<tr><td>BrideAge</td><td><input type=text name="Bage" value="" ></td></tr>
<tr><td>Groom Age</td><td><input type=txt name="BGage" value=""></td></tr>
<tr><td colspan=2 align=center><input type="submit" name="sub"
value="Go"></td></tr>
</table>
cook3.jsp
<% Cookie ck[]=request.getCookies();%>
<table border="1" align="center">
<thead>
<tr><th>Marriage</th><th>Name</th><th>Age</th></tr>
</thead>
<tbody>
<tr>
<td>Bride</td>
<td><%=ck[0].getValue()%></td>
<td><%=request.getParameter("Bage")%></td>
</tr>
<tr>
<td>BrideGroom</td>
<td><%=ck[1].getValue()%></td>
<td><%=request.getParameter("BGage")%></td>
</tr>
</tbody>
</table>
Output of the above application like below:

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 30 of 69

Easy JavaWeb

1.10.

Includes and Forwards


There are some times a JSP may not fulfill client request,then it has to take the help from
other JSP/Servlet.For this we will use RequestDispatcher object.Making use of this object a
JSP will use other JSP/Servlet to fulfil the client request. So that we are achieving reusability
by reusing the same JSP/Servlet in other JSPs.We can achieve this in two ways that we can
include a file at transalation and execution time.
Directive include: is used to include any files content into other desired file. This process
is useful when need a separate header, footer, menu bar, or any common content need to
reuse on other pages.This JSP include can be static or dynamic.Static include in JSP does
include one file content into desired file at translation time, after that JSP page is compiled.
action include:This include execute first file and then output of this file include in desired
file.It will be happen at runtime.If you observe the below example; it will include the output
of the B.jsp in A.jsp every time A.jsp page is requested. We can send parameters to
including file also.
action forward:<jsp:forward> will forward the request to called page same like
<jsp:include>,but here the control will never come back to the caller page where as in case
of <jsp:include>, the control will come back to the caller page.
Example:Demonstration of using directive and action includes.
input.jsp
<html>
<head> <title>Input Details</title></head>
<body>
<form name="f1" action="/JSPBasics/includes/User.jsp" method="get">
username<input name="usr" ><br>
pasword<input type="password" name="pwd"><br>
<input type="submit" value="SubGo" >
</form>
</body>
</html>

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 31 of 69

Easy JavaWeb

User.jsp
<center>
<%@include file="header.jsp" %>
<hr>
<br> <br>
<jsp:include page="body.jsp"/>
<br> <br><br><br>
<hr>
<%@include file="footer.jsp" %>
</center>
header.jsp
<h3>JavaSiva---<i>Care is my motto</i></h3>
body.jsp
<%
String us = request.getParameter("usr");
String pw = request.getParameter("pwd");
out.println("usr: " + us + "<br>");
out.print("pswd: " + pw);
%>
footer.jsp
<h5>Copyrights Reserved</h5>

Example:Demonstration of sending parameters.


A.jsp
Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 32 of 69

Easy JavaWeb
<jsp:include page="/B.jsp">
<jsp:param name="book" value="EasyJavaWeb"/>
</jsp:include>
B.jsp
Here Is the interested book for Java WebTechnologies.<br>
<%
out.println("Favourite Book is "+request.getParameter("book"));
%>
Choosing the required include:There are two include mechanisms available to insert a
file in a JSP page. They are
1. include directive <%@ include file="child.jsp" %>
2. include action <jsp:include page="child.jsp" flush="true" />
The include directive includes the content of the file during the translation phase
where as include action includes the content of the file during execution/request
processing phase.
For include directive, JSP Engine adds the content of the inserted page at translation
phase, so it does not have an impact on performance.
For include action, JSP Engine adds the content of the inserted page at run time
which imposes extra overhead.
1.11.

JavaBeans
The JavaBeans specification defines a set of programming conventions for Java classes that
should be used as pluggable components. Bean is a reusable component which mostly
contains the setter and getter values, we also called it as mutators.To work with java
components we will use <jsp:useBean> which locates or instantiates a Bean with a specific
name and scope.
Syntax:
<jsp:useBean
id="beanInstanceName"
scope="page|request|session|application"
class="package.class"
> child tags </jsp:useBean>
The <jsp:useBean> tag attempts to locates a Bean, or if the Bean does not exist,
instantiates it from a class. To locate or instantiate the Bean, <jsp:useBean> takes the
following steps, in this order:
Attempts to locate a Bean with the scope and name you specify OR defines an
object reference variable with the name you specify.
If it finds the Bean, stores a reference to it in the variable. If you specified type,
gives the Bean that type.
If it does not find the Bean, instantiates it from the class you specify, storing a
reference to it in the new variable with scope you specify.
if it has body tags (between <jsp:useBean> and </jsp:useBean>), executes the
body tags.
The body of a <jsp:useBean> tag often contains a <jsp:setProperty> tag that defines
property values in the object.
Attributes of useBean action:Here I am listing out some of frequently used attributes.

Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 33 of 69

Easy JavaWeb
1.

id="beanInstanceName" which Names a variable that identifies the Bean in the


scope you specify. You can use the variable name in expressions or scriptlets in the
same JSP file.

2.

scope="page|request|session|application" which defines a scope in which the Bean


exists and the variable named in id is available. The default value is page.
a.
b.
c.
d.

3.

page: It means that we can use the Bean within the JSP page.
request: It means that we can use the Bean from any JSP page which
processing the same request.
session: It means that we use the Bean from any Jsp page in the same
session.Means it is per client.
application: It means that we use the Bean from any page in the same
application. Means it will be accessible to all clients.

class="package.class" which instantiates a Bean from a class, using the new


keyword and the class constructor. The class must not be abstract and must have a
public, no-argument constructor.

<jsp:setProperty>:It is a child tag of useBean.We can call bean setter methods.Here is the
syntax.
<jsp:setProperty name = "nameOfBeanInstance"
property="*"| propertyName
value=string | <%= expression%>
param=requestparameter name
>
When you use the <jsp:setProperty> action, the container takes care automatically of the
conversion from text values to the Java types.
<jsp:getProperty>: It is a child tag of useBean.we can call bean getter methods.Here is
the syntax.
<jsp:getProperty name="nameOfBeanInstance" property="propertyName"/>
Example: Demonstration of working with useBean.
Input.html
<HTML>
<head>
<title>Demo Of useBean</title>
</head>
<BODY>
<FORM METHOD=POST ACTION="Collect.jsp">
Name: <INPUT TYPE=TEXT NAME=username><BR>
E-Mail: <INPUT TYPE=TEXT NAME=email><BR>
Age: <INPUT TYPE=TEXT NAME=age><BR>
<INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
UserData.java: This class is a POJO (Stands for Plain Old Java Object) which should be
coded before you are working with <jsp:useBean>.
To collect this data, we define a Java class with fields "username", "email" and "age" and we
provide setter methods "setUsername", "setEmail" and "setAge", as shown. A "setter"
method is just a method that starts with "set" followed by the name of the field. The first
character of the field name is upper-cased. So if the field is "email", its "setter" method will
be "setEmail". Getter methods are defined similarly, with "get" instead of "set". Note that
the setters (and getters) must be public.
package com.javasiva.ajp.examples;
/**
Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 34 of 69

Easy JavaWeb
*
* @author siva
*/
public class UserData {
String username;
String email;
int age;
public void setUsername(String value) {
username = value;
}
public void setEmail(String value) {
email = value;
}
public void setAge(int value) {
age = value;
}
public String getUsername() {
return username;
}
public String getEmail() {
return email;
}
public int getAge() {
return age;
}
}
The method names must be exactly as shown. Once you have defined the class, compile it
and make sure it is available in the WEB-INF/classes folder.
Collect.jsp
All we need to do now is to add the jsp:useBean tag and the jsp:setProperty tag. The
useBean tag will look for an instance of the "com.javasiva.ajp.examples.UserData" in
the session. If the instance is already there, it will update the old instance. Otherwise,
it will create a new instance of com.javasiva.ajp.examples.UserData, and put it in the
session.
The setProperty tag will automatically collect the input data, match names against the
bean method names, and place the data in the bean.

<jsp:useBean id="user" class="com.javasiva.ajp.examples.UserData" scope="session">


<jsp:setProperty name="user" property="username"
value="<%=request.getParameter("username") %>"/>
<jsp:setProperty name="user" property="email" value="siva@javasiva.in"/>
<jsp:setProperty name="user" property="age" param="age"/>
</jsp:useBean>
<A HREF="NextPage.jsp">Show The Values</A>
Note: The point to remember here is that if request parameter names and bean field names
are equal then setter methods will be called automatically using property=*.
NextPage.jsp
Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 35 of 69

Easy JavaWeb
<jsp:useBean id="user" class="com.javasiva.ajp.examples.UserData" scope="session"/>
<HTML>
<BODY>
You Entered<BR><BR>
Name: <jsp:getProperty name="user" property="username"/><BR>
Email: <jsp:getProperty name="user" property="email"/><BR>
Age: <%= user.getAge()%><BR>
</BODY>
</HTML>
Notice that the same useBean tag is repeated. The bean is available as the variable named
"user" of class "com.javasiva.ajp.examples.UserData". The data entered by the End-User is
all collected in the bean.
1.12.

Accessing Database from JSP


It is very simple that how we are accessing database from servlets and applicaton
program,in the same we can access database from JSP.Here I am taking an example to
check whether the user is authenticated or not.
Before working with this scenario, we should create the below table in oracle.
create table customer(custname varchar2(20),
custpwd varchar2(20),custadd varchar2(25),custemail varchar2(25));
Login.html
<form name=login method=post action="/Cart/LoginCheck.jsp">
<table align=center>
<tr><td>UserName</td><td><input type=text name="uid"></td></tr>
<tr><td>Password</td><td><input type=password name=pwd></td></tr>
<tr><td><input type=submit value=Login></td>
</table>
</form>
LoginCheck.jsp
<%@page import="java.sql.*" errorPage="/error.jsp"%>
<%
String su=request.getParameter("uid");
String sp=request.getParameter("pwd");
Connection con=null;
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
PreparedStatement ps=con.prepareStatement("select * from customer where
custname=? and custpwd=?");
ps.setString(1,su);
ps.setString(2,sp);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
out.print(Authenticated);
}
else
{
out.print(Not Authenticated);
}
%>

Call Me@9000387222 for any further assistance..


Sivaramayya@9000387222/9866723206

www. javasiva.in

Page 36 of 69

You might also like