[go: up one dir, main page]

0% found this document useful (0 votes)
12 views187 pages

Unit 5 - Servlet & JSP

A Servlet is a Java-based technology used to create dynamic web applications, extending server capabilities to respond to various types of requests. It operates within a web container, utilizing threads for handling multiple requests efficiently, unlike CGI which starts a new process for each request. Servlets manage HTTP requests and responses, allowing developers to implement methods like doGet() and doPost() to handle form data and client interactions effectively.

Uploaded by

Nimisha Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views187 pages

Unit 5 - Servlet & JSP

A Servlet is a Java-based technology used to create dynamic web applications, extending server capabilities to respond to various types of requests. It operates within a web container, utilizing threads for handling multiple requests efficiently, unlike CGI which starts a new process for each request. Servlets manage HTTP requests and responses, allowing developers to implement methods like doGet() and doPost() to handle form data and client interactions effectively.

Uploaded by

Nimisha Gupta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 187

What is a Servlet?

• Servlet is a technology i.e. used to create web application.


• Servlet is an API that provides many interfaces and classes including
documentations.
• Servlet is an interface that must be implemented for creating any servlet.
• Servlet extends the capabilities of the servers and responds to the incoming
requests. It can respond to any type of requests.
• Servlet is a web component that is deployed on the server to create dynamic
web page.

1
2
CGI(Commmon Gateway Interface)

• CGI technology enables the web server to call an external program


and pass HTTP request information to the external program to
process the request.

• For each request, it starts a new process.

3
4
Disadvantages of CGI

There are many problems in CGI technology:

• If number of clients increases, it takes more time for sending


response.
• For each request, it starts a process and Web server is limited to start
processes.
• It uses platform dependent language e.g. C, C++, perl.

5
Advantage of Servlet

• The web container creates threads for handling the multiple requests
to the servlet.

• Threads have a lot of benefits over the Processes such as they share a
common memory area, lightweight, cost of communication between
the threads are low.

6
7
Benefits of servlet
The basic benefits of servlet are as follows:
• Better performance: because it creates a thread for each request not process.

• Portability: because it uses java language.

• Robust: Servlets are managed by JVM so we don't need to worry about memory
leak, garbage collection etc.

• Secure: because it uses java language

8
Java Servlet
• javax.servlet package can be extended for use with
any application layer protocol
• http is the most popularly used protocol
• javax.servlet.http package is extension of the javax.servlet
package for http protocol
• The Servlet spec allows you to implement separate Java methods
implementing each HTTP method in your subclass of HttpServlet.
• Override the doGet() and/or doPost() method to provide normal
servlet functionality.
• Override doPut() or doDelete() if you want to implement these
methods.
• There's no need to override doOptions() or doTrace().
• The superclass handles the HEAD method all on its own.

9
• To be a servlet, a class should extend HttpServlet and override doGet or doPost, depending
on whether the data is sent by GET or POST.
• If you want the same servlet to handle both GET and POST and to take the same action for
each, you can simply have doGet call doPost, or vice versa.
• Both of these methods take two arguments: an HttpServletRequest and an
HttpServletResponse.
• The HttpServletRequest has methods by which you can find out about incoming
information such as form data, HTTP request headers, and the client’s hostname.
• The HttpServletResponse lets you specify outgoing information such as HTTP status codes
(200, 404, etc.), response headers (Content-Type, Set-Cookie, etc.), and, most importantly,
lets you obtain a PrintWriter used to send the document content back to the client
• doGet and doPost throw two exceptions, you are required to include them in the
declaration.
• Finally, you have to import classes in java.io (for PrintWriter, etc.), javax.servlet (for
HttpServlet, etc.), and javax.servlet.http (for HttpServletRequest and
HttpServletResponse).
Reading Data from a Client
• When the server starts it instantiates servlets
• Server receives HTTP request, determines the need for dynamic
response
• Server selects the appropriate servlet to generate the response,
creates request/response objects, and passes them to a method on
the servlet instance
• Servlet adds information to response object via method calls
• Server generates HTTP response based on information stored in
the response object.
• The browser uses two methods to pass this information to a web
server. These methods are the GET Method and POST Method.

12
GET Method (doGet())
• The GET method sends the encoded user information appended to the
page request. The page and the encoded information are separated by
the ?(question mark) symbol as follows −
http://www.test.com/hello?key1 = value1&key2 = value2
POST Method (doPost())
• A generally more reliable method of passing information to a backend program is the
POST method.
• This packages the information in exactly the same way as the GET method, but instead
of sending it as a text string after a ? (question mark) in the URL it sends it as a
separate message.
• This message comes to the backend program in the form of the standard input which
you can parse and use for your processing.
• Servlet handles such types of requests using doPost() method.

13
• To build HTML, you need two additional steps:
• Tell the browser that you’re sending back HTML, and
• Modify the println statements to build a legal Web page.
• You accomplish the first step by setting the HTTP Content-Type
response header.
response.setContentType("text/html");

• The second step in writing a servlet that builds an HTML


document is to have your println statements output HTML
• When the servlet is first created, its init method is invoked, so that is where
you put the one-time setup code.
• After this, each user request results in a thread that calls the service method
of the previously created instance.
• Multiple concurrent requests normally result in multiple threads calling
service simultaneously, although your servlet can implement a special
interface that stipulates that only a single thread is permitted to run at any
one time.
• The service method then calls doGet, doPost, or another doXxx method,
depending on the type of HTTP request it received.
• Finally, when the server decides to unload a servlet, it first calls the
servlet’s destroy method
• The init method is called when the servlet is first created and is not called again for each user
request. So, it is used for one-time initializations.
• The servlet can be created when a user first invokes a URL corresponding to the servlet or when
the server is first started, depending on how you have registered the servlet with the Web server.
• There are two versions of init: one that takes no arguments and one that takes a ServletConfig
object as an argument.
• The first version is used when the servlet does not need to read any settings that vary from server to
server. The method definition looks like this:

• The second version of init is used when the servlet needs to read server-specific settings before it can complete the
initialization. For example, the servlet might need to know about database settings, password files, server-specific
performance parameters, hit count files, or serialized cookie data from previous requests.

• ServletConfig has a getInitParameter method with which you can look up initialization
parameters associated with the servlet.
• Each time the server receives a request for a servlet, the server spawns a new thread and calls service.
• The service method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet,
doPost, doPut, doDelete, etc., as appropriate.
• Now, if you have a servlet that needs to handle both POST and GET requests identically, you may be
tempted to override service directly as below, rather than implementing both doGet and doPost
• The server may decide to remove a previously loaded servlet instance, perhaps because
it is explicitly asked to do so by the server administrator, or perhaps because the servlet
is idle for a long time.
• Before it does, however, it calls the servlet’s destroy method.
• This method gives your servlet a chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform other such cleanup
activities.
• Be aware, however, that it is possible for the Web server to crash.
• After all, not all Web servers are written in reliable programming languages like Java;
some are written in languages where it is easy to read or write off the ends of arrays,
make illegal typecasts, or have dangling pointers due to memory reclamation errors.
Servlet
Container

Create Thread Pool


Thread Thread

Instantiate servlet
Servlet
HTTP
Call init ( ) method Perform
Request 1
Initialization
Allocate request to thread Call service ( ) method

HTTP
Request 2 Allocate request to thread Call service ( ) method
Perform Service
Shutdown
Initiated
Block all further requests Wait
HTTP for active threads to end Perform Service
Response 1

Terminate thread pool

call destroy ( ) method


HTTP Perform
Response 2 cleanup
terminate servlet
Servlet destroyed
& garbage collected
Container shutdown

21
Handling the Client Request
• If you’ve ever used a search engine, visited an on-line bookstore,
tracked stocks on the Web, or asked a Web-based site for quotes on
plane tickets, you’ve probably seen funny-looking URLs like
http://host/path?user=Marty+Hall&origin=bwi&dest=lax.
• The part after the question mark (i.e., user=Marty+Hall&origin=
bwi&dest=lax) is known as form data (or query data) and is the most
common way to get information from a Web page to a server-side
program.
• Form data can be attached to the end of the URL after a question mark
(as above), for GET requests, or sent to the server on a separate line,
for POST requests.
Handling the Client Request(Contd…)
• One of the nice features of servlets is that all of this form parsing is handled automatically.
• You simply call the getParameter method of the HttpServletRequest, supplying the case-sensitive parameter
name as an argument.
• You use getParameter exactly the same way when the data is sent by GET as you do when it is sent by
POST.
• The servlet knows which request method was used and automatically does the right thing behind the scenes.
• The return value is a String corresponding to the URL-decoded value of the first occurrence of that
parameter name.
• An empty String is returned if the parameter exists but has no value, and a null is returned if there was no
such parameter.
• If the parameter could potentially have more than one value, you should call getParameterValues (which
returns an array of strings) instead of getParameter (which returns a single string).
• The return value of getParameterValues is null for nonexistent parameter names and is a one-element array
when the parameter has only a single value.
• Parameter names are case sensitive so, for example, request.getParameter("Param1") and
request.getParameter("param1") is not interchangeable
• Use getParameterNames to get this list in the form of an Enumeration, each entry of which can be cast to a
String and used in a getParameter or getParameterValues call.
Reading All Parameters
• First, the servlet looks up all the parameter names by the getParameterNames
method of HttpServletRequest.
• This method returns an Enumeration that contains the parameter names in an
unspecified order.
• Next, the servlet loops down the Enumeration in the standard manner, using
hasMoreElements to determine when to stop and using nextElement to get each
entry.
• Since nextElement returns an Object, the servlet casts the result to a String and
passes that to getParameterValues, yielding an array of strings.
• If that array is one entry long and contains only an empty string, then the
parameter had no values and the servlet generates an italicized “No Value” entry.
• If the array is more than one entry long, then the parameter had multiple values
and the values are displayed in a bulleted list.
• Otherwise, the one main value is placed into the table unmodified.
Handling the Client Request:HTTP Request
Headers
• One of the keys to creating effective servlets is understanding how to manipulate the
HyperText Transfer Protocol (HTTP).
• Form data results directly from user input and is sent as part of the URL for GET requests
and on a separate line for POST requests.
• Request headers, on the other hand, are indirectly set by the browser and are sent
immediately following the initial GET or POST request line.
• For instance, the following example shows an HTTP request that might result from
submitting a book-search request to a servlet at http://www.somebookstore.com/search.
• The request includes the headers Accept, Accept-Encoding, Connection, Cookie, Host,
Referer, and User-Agent, all of which might be important to the operation of the servlet,
but none of which can be derived from the form data or deduced automatically: the servlet
needs to explicitly read the request headers to make use of this information.
Reading Request Headers from Servlets
• Reading headers is straightforward; just call the getHeader method of
HttpServletRequest, which returns a String if the specified header was supplied on this
request, null otherwise.
• Header names are not case-sensitive. So, for example,
request.getHeader("Connection") and request.getHeader("connection") are
interchangeable.
• Although getHeader is the general-purpose way to read incoming headers, there are a
couple of headers that are so commonly used that they have special access methods in
HttpServletRequest.
• getCookies: The getCookies method returns the contents of the Cookie header, parsed
and stored in an array of Cookie objects.
• getAuthType and getRemoteUser: The getAuthType and getRemoteUser methods
break the Authorization header into its component pieces.
• getContentLength: The getContentLength method returns the value of the Content-
Length header (as an int).
Reading Request Headers from Servlets
• getContentType: The getContentType method returns the value of the
Content-Type header (as a String).
• getDateHeader and getIntHeader: The getDateHeader and
getIntHeader methods read the specified header and then convert them
to Date and int values, respectively.
• getHeaderNames: Rather than looking up one particular header, you can
use the getHeaderNames method to get an Enumeration of all header
names received on this particular request.
• getHeaders: In most cases, each header name appears only once in the
request. Occasionally, however, a header can appear multiple times, with
each occurrence listing a separate value. Accept-Language is one such
example.
Reading Request Headers from Servlets
• Finally, in addition to looking up the request headers, you can get
information on the main request line itself, also by means of methods
in HttpServletRequest.
• getMethod: The getMethod method returns the main request
method.
• getRequestURI: The getRequestURI method returns the part of the
URL that comes after the host and port but before the form data.
For example, for a URL of
http://randomhost.com/servlet/search.BookSearch, getRequestURI
would return /servlet/search.BookSearch.
• getProtocol: the getProtocol method returns the third part of the
request line, which is generally HTTP/1.0 or HTTP/1.1. Servlets
Request Headers
Accept: This header specifies the MIME types that the browser or other clients can handle. Values of
image/png or image/jpeg are the two most common possibilities.
Accept-Charset: This header specifies the character sets the browser can use to display the
information. For example ISO-8859-1.
Accept-Encoding: This header specifies the types of encodings that the browser knows how to
handle. Values of gzip or compress are the two most common possibilities.
Accept-Language: This header specifies the client's preferred languages in case the servlet can
produce results in more than one language. For example en, en-us, ru, etc
Authorization: This header is used by clients to identify themselves when accessing password-
protected Web pages.
Connection: This header indicates whether the client can handle persistent HTTP connections.
Persistent connections permit the client or other browsers to retrieve multiple files with a single
request. A value of Keep-Alive means that persistent connections should be used.
Content-Length: This header is applicable only to POST requests and gives the size of the POST
data in bytes.
Cookie: This header returns cookies to servers that previously sent them to the browser.

38
Request Headers
Connection: This header indicates whether the client can handle persistent HTTP connections.
Persistent connections permit the client or other browsers to retrieve multiple files with a single
request. A value of Keep-Alive means that persistent connections should be used.
Content-Length: This header is applicable only to POST requests and gives the size of the POST
data in bytes.
Cookie: This header returns cookies to servers that previously sent them to the browser.
Host: This header specifies the host and port as given in the original URL.
If-Modified-Since: This header indicates that the client wants the page only if it has been changed
after the specified date. The server sends a code, 304 which means Not Modified header if no newer
result is available.
If-Unmodified-Since: This header is the reverse of If-Modified-Since; it specifies that the operation
should succeed only if the document is older than the specified date.
Referer: This header indicates the URL of the referring Web page. For example, if you are on Web
page 1 and click on a link to Web page 2, the URL of Web page 1 is included in the Referrer header
when the browser requests Web page 2.
User-Agent: This header identifies the browser or other client making the request and can be used to
return different content to different types of browsers.
39
Response Headers
Allow: This header specifies the request methods (GET, POST, etc.) that the server supports.

Cache-Control: This header specifies the circumstances in which the response document can safely
be cached. It can have values public, private or no-cache etc. Public means the document is
cacheable, Private means the document is for a single user and can only be stored in private (non-
shared) caches and no cache means the document should never be cached.

Connection: This header instructs the browser whether to use persistent HTTP connections or not. A
value of close instructs the browser not to use persistent HTTP connections and keepalive means
using persistent connections.

Content-Disposition: This header lets you request that the browser ask the user to save the response
to disk in a file of the given name.

Content-Encoding: This header specifies the way in which the page was encoded during
transmission.

Content-Language: This header signifies the language in which the document is written. For
example en, en-us, ru, etc
Response Headers
Content-Length: This header indicates the number of bytes in the response. This information is needed
only if the browser is using a persistent (keep-alive) HTTP connection.

Content-Type: This header gives the MIME (Multipurpose Internet Mail Extension) type of the
response document.

Expires: This header specifies the time at which the content should be considered out-of-date and thus
no longer be cached.

Last-Modified: This header indicates when the document was last changed. The client can then cache
the document and supply a date by an If-Modified-Since request header in later requests.

Location: This header should be included with all responses that have a status code in the 300s. This
notifies the browser of the document address. The browser automatically reconnects to this location and
retrieves the new document.

Refresh: This header specifies how soon the browser should ask for an updated page. You can specify
the time in the number of seconds after which a page would be refreshed.
Response Headers
Retry-After: This header can be used in conjunction with a 503 (Service Unavailable) response to tell
the client how soon it can repeat its request.

Set-Cookie: This header specifies a cookie associated with the page.


Response Headers
Retry-After: This header can be used in conjunction with a 503 (Service Unavailable) response to tell
the client how soon it can repeat its request.

Set-Cookie: This header specifies a cookie associated with the page.


Handling Cookies
• Cookies are small bits of textual information that a Web server sends to a browser and that the
browser returns unchanged when later visiting the same Web site or domain.
• By letting the server read the information it sent the client previously, the site can provide visitors
with a number of conveniences such as presenting the site the way the visitor previously customized
it or letting identifiable visitors in without their having to enter a password.
• Most browsers avoid caching documents associated with cookies, so the site can return different
content each time.

▪ Benefits of Cookies
Identifying a User During an E-commerce Session
Avoiding Username and Password
Customizing a Site
Focusing Advertising
Problems with Cookies
• Cookies are never interpreted or executed in any way and thus cannot be
used to insert viruses or attack your system.
• Furthermore, since browsers generally only accept 20 cookies per site and
300 cookies total and since each cookie can be limited to 4 kilobytes,
cookies cannot be used to fill up someone’s disk or launch other denial of
service attacks.
• However, even though cookies don’t present a serious security threat, they
can present a significant threat to privacy.
• First, some people don’t like the fact that search engines can remember that they’re the user
who usually does searches on certain topics. For example, they might search for job openings
or sensitive health data and don’t want some banner ad tipping off their coworkers the next
time they do a search. Even worse, two sites can share data on a user by each loading small
images of the same third-party site, where that third party uses cookies and shares the data
with both original sites.
• A second privacy problem occurs when sites rely on cookies for overly sensitive data. For
example, some of the big online bookstores use cookies to remember users and let you order
without reentering much of your personal information.
• To send cookies to the client,
• a servlet should create one or more cookies with designated names and values
with new Cookie(name, value),
• set any optional attributes with cookie.setXxx (readable later by
cookie.getXxx), and
• insert the cookies into the response headers with response.addCookie(cookie).
• To read incoming cookies,
• a servlet should call request.getCookies, which returns an array of Cookie
objects corresponding to the cookies the browser has associated with your site
(this is null if there are no cookies in the request).
• In most cases, the servlet loops down this array until it finds the one whose
name (getName) matches the name it had in mind, then calls getValue on that
Cookie to see the value associated with that name.
Creating Cookies
You create a cookie by calling the Cookie constructor, which takes two strings: the
cookie name and the cookie value. Neither the name nor the value should contain white
space or any of the following characters:
[]()=,"/?@:;

Cookie Attributes
Before adding the cookie to the outgoing headers, you can set various characteristics of
the cookie by using one of the following setXxx methods, where Xxx is the name of the
attribute you want to specify.
Each setXxx method has a corresponding getXxx method to retrieve the attribute value.
Except for name and value, the cookie attributes apply only to outgoing cookies from the
server to the client; they aren’t set on cookies that come from the browser to the server.
public int getMaxAge() & public void setMaxAge(int lifetime)
• These methods tell how much time (in seconds) should elapse before the cookie expires.
• A negative value, which is the default, indicates that the cookie will last only for the
current session (i.e. until the user quits the browser) and will not be stored on disk.
• LongLivedCookie class defines a subclass of Cookie with a maximum age automatically
set one year in the future.
• Specifying a value of 0 instructs the browser to delete the cookie.
public String getName() & public void setName(String cookieName)
• This pair of methods gets or sets the name of the cookie.
• The name and the value are the two pieces you virtually always care about.
• However, since the name is supplied to the Cookie constructor, you rarely need to call
setName.
• On the other hand, getName is used on almost every cookie received on the server.
• Since the getCookies method of HttpServletRequest returns an array of Cookie objects,
it is common to loop down this array, calling getName until you have a particular name,
then check the value with getValue.
public String getValue() & public void setValue(String cookieValue)
• The getValue method looks up the value associated with the cookie; the setValue method specifies
it.
• Again, the name and the value are the two parts of a cookie that you almost always care about,
although in a few cases, a name is used as a boolean flag and its value is ignored (i.e., the existence
of a cookie with the designated name is all that matters).
The cookie is inserted into a Set-Cookie HTTP response header by means of the addCookie method of
HttpServletResponse. The method is called addCookie, not setCookie, because any previously
specified Set-Cookie headers are left alone and a new header is set. Here's an example:

To send cookies to the client, you create a Cookie, then use addCookie to send a Set-Cookie HTTP
response header.

To read the cookies that come back from the client, you call getCookies on the HttpServletRequest.
This call returns an array of Cookie objects corresponding to the values that came in on the Cookie
HTTP request header.

If there are no cookies in the request, getCookies returns null. Once you have this array, you typically
loop down it, calling getName on each Cookie until you find one matching the name you have in
mind. You then call getValue on the matching Cookie and finish with some processing specific to the
resultant value.
• HTTP is a “stateless” protocol:
• Each time a client retrieves a Web page, it opens a separate connection to the Web server,
• The server does not automatically maintain contextual information about a client.

• Even with servers that support persistent (keep-alive) HTTP connections and keep a socket
open for multiple client requests that occur close together in time, there is no built-in
support for maintaining contextual information.

• This lack of context causes a number of difficulties.

• For example,
• when clients at an online store add an item to their shopping carts, how does the server know
what’s already in them?
• Similarly, when clients decide to proceed to checkout, how can the server determine which
previously created shopping carts are theirs?
• There are three typical solutions to this problem: cookies, URL-rewriting, and hidden form
field.
• With this approach, the client appends some extra data on the end of each URL
that identifies the session, and the server associates that identifier with data it has
stored about that session.
• For example, with http://host/path/file.html;jsessionid=1234, the session
information is attached as jsessionid=1234.
• This is also an excellent solution and even has the advantage that it works when
browsers don’t support cookies or when the user has disabled them.
• You have to be very careful that every URL that references your site and is
returned to the user (even by indirect means like Location fields in server
redirects) has the extra information appended. And, if the user leaves the session
and comes back via a bookmark or link, the session information can be lost
• HTML forms can have an entry that looks like the following:

• This entry means that, when the form is submitted, the specified name
and value are included in the GET or POST data.
• This hidden field can be used to store information about the session but
it has the major disadvantage that it only works if every page is
dynamically generated.
• Servlets provide an outstanding technical solution: the HttpSession API.

• This high-level interface is built on top of cookies or URL-rewriting.

• In fact, most servers 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 arbitrary objects that are associated
with each session.
• Using sessions in servlets is straightforward.
• It involves:
• looking up the session object associated with the current request,
• creating a new session object when necessary,
• looking up information associated with a session,
• storing information in a session, and discarding completed or
abandoned sessions.
• Finally, if you return any URLs to the clients that reference your site and
URL-rewriting is being used, you need to attach the session information
to the URLs.
• You look up the HttpSession object by calling the getSession method of HttpServletRequest.
• Behind the scenes,
• the system extracts a user ID from a cookie or attached URL data,
• then uses that as a key into a table of previously created HttpSession objects.
• But this is all done transparently to the programmer: you just call getSession.
• If getSession returns null, this means that the user is not already participating in a session, so you
can create a new session.
• Creating a new session in this case is so commonly done that there is an option to automatically
create a new session if one doesn’t already exist.
• Just pass true to getSession. Thus, your first step usually looks like this:

• If you care whether the session existed previously or is newly created, you can use isNew to
check.
• HttpSession objects live on the server; they’re just automatically associated with the
client by a behind-the-scenes mechanism like cookies or URL-rewriting.
• These session objects have a built-in data structure that lets you store any number of
keys and associated values.
public Object getAttribute(String name): extract a previously stored value from a session object. Return
null if there is no value associated with the given name.

public void setAttribute(String name, Object value): associate a value with a name.

public void removeAttribute(String name): remove any values associated with the designated name.

public boolean isNew(): returns true if the client (browser) has never seen the session, usually because it
was just created rather than being referenced by an incoming client request. It returns false for preexisting
sessions.

public void invalidate(): invalidates the session and unbinds all objects associated with it.
public int getMaxInactiveInterval() & public void setMaxInactiveInterval(int seconds)
These methods get or set the amount of time, in seconds, that a session should go without
access before being automatically invalidated.
A negative value indicates that the session should never time out. Note that the time out is
maintained on the server and is not the same as the cookie expiration date, which is sent to
the client.

Sessions will automatically become inactive when the amount of time between client accesses
exceeds the interval specified by getMaxInactiveInterval.

When this happens, any objects bound to the HttpSession object automatically get unbound.
Rather than waiting for sessions to time out, you can explicitly deactivate a session through the
use of the session’s invalidate method.
Sessions

65
Sessions

Server sends back


new unique
session ID when
the request has
none

66
Sessions

Client that supports


session stores the
ID and sends it
back to the server
in subsequent
requests

67
Sessions

Server knows
that all of these
requests are
from the same
client. The
set of requests
is known as a
session.

68
Sessions

And the server


knows that all
of these
requests are
from a different
client.

69
Sessions

Returns HttpSession object associated


with this HTTP request.
• Creates new HttpSession object if no
session ID in the request or no object with
this ID exists
• Otherwise, returns previously created
object

70
Sessions

Boolean indicating whether returned the object


was newly created or already
existed.

71
Sessions

Incremented once per session

72
Sessions

Three web
pages produced
by a single servlet

73
Sessions

74
Sessions

75
Sessions

76
Sessions

77
Sessions

,,,

78
Sessions

,,, Session attribute is a


name/value pair

79
Sessions

,,,

Session attribute will


have null value until
a value is assigned

80
Sessions

,,,

Generate
sign-in form
if session is
new or
signIn
attribute has no value,
weclome-back page
otherwise.

81
Sessions

Sign-in form

Welcome-back
page

82
Sessions

Second argument
(“Greeting”) used as
action attribute value
(relative URL)

83
Sessions

Form will be sent using POST HTTP


method (doPost() method will be called)

84
Sessions

Text field containing


user name is named
signIn

85
Sessions

86
Sessions


Retrieve
signIn
parameter value

87
Sessions

Normal
processing:
signIn
parameter
is present in
HTTP request

88
Sessions

Generate
HTML for
response

89
Sessions

Thank-you page Must escape


XML special
characters in
user input

90
Sessions

Assign a
value to the
signIn session
attribute

91
RequestDispatcher and Page Redirection in
Servlets
• The RequestDispatcher is an interface that defines an object to receive request
from the client and sends them to any resource on the server.
• It implements an object to wrap together different types of resources in Servlet
container.
RequestDispatcher Methods
The RequestDispatcher interface provides two methods:
Methods Description
public void forward(ServletRequest It forwards a client request from a servlet
request, ServletResponse response) to another resource (servlet, JSP file,
HTML file) on the server.

public void include(ServletRequest Includes the content of a resource


request, ServletResponse response) (Servlet, JSP, pages, HTML file) in
the response.
Getting the Object of RequestDispatcher
ServletRequest interface provides the getRequestDispatcher( ) method to returns the object of
RequestDispatcher.

Example

RequestDispatcher rd = request.getRequestDispatcher("index.html"); rd.forward(request,


response);

OR

RequestDispatcher rd = request.getRequestDispatcher("index.html"); rd.include(request,


response);
Page Redirection
• The Page redirection is the process of redirecting the response to another
resource.
• It is used to move the document to the new location for load balancing or
simple randomization.
• The sendRedirect( ) method is the method of HttpServletResponse
interface.
• It is used to redirect response to another resource (servlet, jsp or HTML
file).
For example:
response.sendRedirect("index.html");
Difference between forward( ) method and sendRedirect( ) method
forward( ) sendRedirect( )
Used to forward the resources Used to redirect the resources to different servers or
available within the server. domains.
The forward( ) method is executed on The sentRedirect( ) method is executed on the
the server side. client side.

The forward( ) method is faster than It is slower because each time a new request is
sendRedirect( ). created, old one is lost.
The transfer of control is done by The transfer of control is assigned to the browser
container and client/browser is not and a new request to the given URL is initiated.
involved.
The request is shared by the target New request is created for the server resource.
resource.
It is declared in RequestDispatcher It is declared in HttpServletResponse.
interface.
Example : Illustrating the sendRedirect( ) method for page redirecting in
Servlet
//SendRedirectDemo.java
import java.io.*; import javax.servlet.*;
import javax.servlet.http.*;
public class SendRedirectDemo extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
response.sendRedirect("http://anyserver.com/")
pw.close();
}
}
Architecture of JSP
Life Cycle of JSP Page
• Translation of JSP page.
• Compilation of JSP page.
• Loading the class.
• Instantiation of Servlet objects.
• Initialization by calling jspInit( ) method.
• Request Processing by calling _jspService( ) method.
• Destruction by calling jspDestroy( ) method.
Example
jspInit( ) method
public void jspInit( ){
//code
}
_jspService( ) method
void _jspService(HttpServletRequest request, HttpServletResponse response){
//service code
}
jspDestroy( ) method
public void jspDestroy( ){
//cleanup code
}
• Java Server Pages (JSP) technology enables you to mix regular, static HTML with
dynamically generated content from servlets.
• You simply write the regular HTML in the normal manner, using familiar Web-page-building
tools.
• You then enclose the code for the dynamic parts in special tags, most of which start with <% and
end with %>.
• For example, here is a section of a JSP page that results in “Thanks for ordering Core Web
Programming” for a URL of http://host/OrderConfirmation.jsp?title=Core+Web+Programming:

• Aside from the regular HTML, there are three main types of JSP constructs that you embed in a
page: scripting elements, directives, and actions.
• Scripting elements let you specify Java code that will become part of the resultant servlet. To
simplify the scripting elements, you have access to a number of predefined variables
• Directives let you control the overall structure of the servlet, and
• Actions let you specify existing components that should be used and otherwise control the behavior of
the JSP engine.
JSP Comments
• JSP comment is text or statement that is not considered by JSP
container.
• JSP comments are hidden in JSP page source and ignored by JSP
container.
• Syntax:
<%-- JSP comment --%>
request:the HttpServletRequest
response:the HttpServletResponse
session: the HttpSession associated with the request
out: the PrintWriter (a buffered version called JspWriter) used to send output to the client
JSP scriptlets let you insert arbitrary code into the servlet’s _jspService method (which is
called by service).

Scriptlets have the following form:

Scriptlets have access to the same automatically defined variables as expressions. So, for
example, if you want output to appear in the resultant page, you would use the out
variable, as in the following example.

In this particular instance, you could have accomplished the same effect more easily by
using the following JSP expression:
Attached GET data: <%= request.getQueryString() %>
A JSP declaration lets you define methods or fields that get inserted into the main body
of the servlet class (outside of the _jspService method that is called by service to process
the request). A declaration has the following form:
To simplify code in JSP expressions and scriptlets, you are supplied with eight automatically
defined variables, sometimes called implicit objects. Since JSP declarations result in code that
appears outside of the _jspService method, these variables are not accessible in declarations.
The available variables are request, response, out, session, application, config, pageContext,
and page.

request: This variable is the HttpServletRequest associated with the request; it gives you access to
the request parameters, the request type (e.g., GET or POST), and the incoming HTTP headers
(e.g., cookies).

response: This variable is the HttpServletResponse associated with the response to the client.

out: This is the PrintWriter used to send output to the client. However, to make the response object
useful, this is a buffered version of PrintWriter called JspWriter.

session: This variable is the HttpSession object associated with the request. Recall that sessions
are created automatically, so this variable is bound even if there is no incoming session reference
application : This variable is the ServletContext as obtained via
getServletConfig().getContext(). Servlets and JSP pages can store persistent data
in the ServletContext object rather than in instance variables. ServletContext has
setAttribute and getAttribute methods that let you store arbitrary data associated
with specified keys.
config: This variable is the ServletConfig object for this page.
pageContext: JSP introduced a new class called PageContext to give a single point
of access to many of the page attributes and to provide a convenient place to store
shared data. The pageContext variable stores the value of the PageContext object
associated with the current page.
page: This variable is simply a synonym for this and is not very useful in the Java
programming language. It was created as a place holder for the time when the
scripting language could be something other than Java.
exception: It is an instance of Exception, the Java class used for throwing
exceptions when something goes wrong with the code.
JSP request implicit object
• The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp
request by the web container.

• It can be used to get request information such as parameter, header information, remote
address, server name, server port, content type, character encoding etc.

• It can also be used to set, get and remove attributes from the jsp request scope.

• Let's see the simple example of request implicit object where we are printing the name of
the user with welcome message(Next slide).
Example of JSP request implicit object
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

welcome.jsp
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
JSP response implicit object
• In JSP, response is an implicit object of type HttpServletResponse.

• The instance of HttpServletResponse is created by the web container for each jsp request.

• It can be used to add or manipulate response such as redirect response to another resource,
send error etc.

• Let's see the example of response implicit object where we are redirecting the response to
the Google.
Example of response implicit object
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

welcome.jsp
<%
response.sendRedirect("http://www.google.com");
%>
JSP config implicit object
• In JSP, config is an implicit object of type ServletConfig.

• This object can be used to get initialization parameter for a particular JSP page.

• The config object is created by the web container for each jsp page.

• Generally, it is used to get initialization parameter from the web.xml file.


Example of config implicit object (web.xml)
<web-app>

<servlet>
<servlet-name> greetings </servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>greetings</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

</web-app>
Example of config implicit object(Contd…)
index.html
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp

<%
out.print("Welcome "+request.getParameter("uname"));
String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);
%>
JSP application implicit object
• In JSP, application is an implicit object of type ServletContext.

• The instance of ServletContext is created only once by the web container when
application or project is deployed on the server.

• This object can be used to get initialization parameter from configuaration file
(web.xml).

• It can also be used to get, set or remove attribute from the application scope.

• This initialization parameter can be used by all jsp pages


Example of application implicit object (web.xml)
<web-app>

<servlet>
<servlet-name> greetings </servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
</servlet>

<servlet-mapping>
<servlet-name> greetings </servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>

<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>

</web-app>
Example of application implicit object
index.html

<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

welcome.jsp

<%

out.print("Welcome "+request.getParameter("uname"));

String driver=application.getInitParameter("dname");
out.print("driver name is="+driver);

%>
JSP session implicit object
• In JSP, session is an implicit object of type HttpSession.

• This object can use to set, get or remove attribute or to get session
information.
Example of session implicit object
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>
Example of session implicit object
second.jsp
<html>
<body>
<%

String name=(String)session.getAttribute("user");
out.print("Hello "+name);

%>
</body>
</html>
JSP pageContext implicit object
• In JSP, pageContext is an implicit object of type PageContext class.

• The pageContext object can be used to set, get or remove attribute from one of the
following scopes:

• page
• request
• session
• application
Example of pageContext implicit object
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
pageContext.setAttribute("user", name, PageContext.SESSION_SCOPE);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>
Example of pageContext implicit object
second.jsp
<html>
<body>
<%

String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
out.print("Hello "+name);

%>
</body>
</html>
JSP page implicit object
• In JSP, page is an implicit object of type Object class.

• This object is assigned to the reference of auto generated servlet class.

• It is written as:

Object page=this;

• For using this object it must be cast to Servlet type. For example:

<% (HttpServlet)page.log("message"); %>

• Since, it is of type Object it is less used because you can use this object directly in
jsp. For example:

<% this.log("message"); %>


JSP exception implicit object
In JSP, exception is an implicit object of type java.lang.Throwable class.
This object can be used to print the exception. But it can only be used in error pages.
Example of exception implicit object:
error.jsp
<%@ page isErrorPage="true" %>
<html>
<body>
Sorry following exception occured:<%= exception %>
</body>
</html>
Form Processing in JSP
• Forms are the basic components that help us interact with web pages.
• The form processing became very easy with the help of JSP. The browser uses the GET
method and POST method for passing the information to the webserver.
GET Method
• The GET method is used to send the encoded user information appended to the page
URL. Each encoded information is separated by '?' character.
• GET is a default method to send information to web server. We should avoid using GET
method to send sensitive information like as password etc.
For example:
http://www.abcserver.com/hello?name=amit&city=kanpur&prof=doctor
GET Method Example
<html>
<head>
<title>Reading data by Using GET method</title>
</head>
<body>
<h1>GET method</h1>
<ul>
<li><p><b>Name:</b>
<%= request.getParameter("name")%>
</p></li>
<li><p><b>City:</b>
<%= request.getParameter("city")%>
</p></li>
<li><p><b>Profession:</b>
<%= request.getParameter("prof")%>
</p></li></ul></body></html>
POST Method
The POST method is used to send large amount of data on web server. When we want to send any
sensitive data on web page, the POST method should be used as instead of sending text string in
URL, it sends the encrypted message.
Example: Implementing POST method using Form
//welcome.html
<html>
<head>
<title>Using POST method</title>
</head>
<body>
<h2>Using POST method</h2>
<form action = "welcome.jsp" method = "POST">
Name: <input type = "text" name = "name"/>
City: <input type = "text“ name = "city"/>
Job:<input type = "text" name = "job">
<input type = "submit" value = "Submit">
</form></body></html>
//welcome.jsp
<html>
<head>
<title>JSP page using POST method</title>
</head>
<body>
Name: <%= request.getParameter ("name") %>
City: <%= request.getParameter ("city") %>
Job: <%= request.getParameter ("job") %>
</body></html>
JSP Directives
• JSP directive affects the overall structure of the servlet that results from the JSP page. The
following templates show the two possible forms for directives.

• In JSP, there are three types of directives: page, include, and taglib.
• page directive lets you control the structure of the servlet by importing classes, customizing
the servlet superclass, setting the content type, and the like. A page directive can be placed
anywhere within the document.
• include directive lets you insert a file into the servlet class at the time the JSP file is
translated into a servlet. An include directive should be placed in the document at the point
at which you want the file to be inserted.
• taglib directive is used to define custom markup tags.
page directive
• The page directive allows applying different attributes to be added in JSP.
• These attributes give special processing information to the JSP container.
Following are the page directive attribute:
Attribute Description
Import list of packages, classes and interfaces in servlet class definition.
import
Example: <%@ page import = "java.util.Date" %>
Used to extend the parent class that will be generated by Servlet.
extends
Example: <%@ page extends = "mypackage.DemoClass"%>
Defines which scripting language to be used in the page.
language Example: <%@ page language = "value"%>
Specifies the JSP page participating in an HTTP session.
session
Example: <%@ page session = "true"%>
Specifies a buffer model to handle output stream generated by JSP page.
buffer
Example: <%@ page buffer = "4kb"%>
Specifies whether the expression will be evaluated or not in JSP page.
isELIgnored
Example: <%@ page isELIngored="true" %>
Specifies that buffer should be flushed automatically. The default value of autoFlush attribute
autoFlush is ‘true’.
Example: <%@ page autoFlush = "false"%>
Sets the information of the JSP page which is retrieved later by using getServletInfo( )
info method.
Example: <%@ page info = “By PSIT"%>
Sets the content of the JSP page.
contentType Example: <%@ page contentType="text/html"%>
It is used to define the threading model for the JSP page which is generated by Servlet
isThreadSafe because JSP and servlet both are thread safe.
Example: <%@ page isThreadSafe="false"%>
Define the error page, if any error generates in current page, it will be redirected to the error
errorPage page.
Example: <%@ page errorPage="erroropage.jsp"%>
Defines whether the current JSP page is error page or not.
isErrorPage Example: <%@ page isErrorPage="true" %>
include directive
▪ The include directive is used to insert a file like a JSP file, HTML file or text file.
▪ It will parse the JSP elements during the translation phase.
▪ The main advantage of the include directive is code reusability functionality.

Syntax:
<%@ include file="resourceName" %>
Example
<%@ include file = "header.jsp">
taglib directive
• It is used to define a tag library that contains many custom tags.
• JSP technology supports the development of reusable components called custom actions.
• The custom tags can be customized by passing the attribute from invoking page.
• It can be accessed by all the available objects on the JSP page.
• Syntax:
• <%@ taglib prefix="prefixOfTag" uri="uriOfTagLibrary" %>
Example
<%@ taglib prefix="myTag" uri="http://www.abcserver.com/java- technologies.htm" %>
<body>
Welcome, <myTag:userName / >
</body>
Exception Handling
• Exception is an event that arises during the execution of the program.
• It terminates the program abnormally.
• Exception handling is the process of handling the abnormal termination of the
program.
• Exception handling in JSP is easier than in Java
technology.
• JSP also uses the same exception class object.
There are two ways to perform Exception Handling in JSP:
• Using isErrorPage and errorPage attribute of page directive.
• Using <error-page> tag in Deployment Descriptor(web.xml)
Example : Exception handling using isErrorPage & errorPage attribute
In this case, you must define and create a page to handle the exceptions, as in the error.jsp
page.
The pages where may occur exception, define the errorPage attribute of page directive, as in
the process.jsp page.
There are 3 files:
•index.jsp for input values
•process.jsp for dividing the two numbers and displaying the result
•error.jsp for handling the exception
index.jsp
<form action="process.jsp">
First Number :<input type="text" name="n1" /><br/><br/>
Second Number:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>

process.jsp
<%@ page errorPage="error.jsp" %>

<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
error.jsp

<%@ page isErrorPage="true" %>

<h3>Sorry an exception occured!</h3>

Exception is: <%= exception %>


Example of exception handling in jsp by specifying the error-page element in web.xml file
• This approach is better because you don't need to specify the errorPage attribute in each jsp page.
• Specifying the single entry in the web.xml file will handle the exception.
• In this case, either specify exception-type or error-code with the location element.
• If you want to handle all the exception, you will have to specify the java.lang.Exception in the
exception-type element. Let's see the simple example:
• There are 4 files:
• web.xml file for specifying the error-page element
• index.jsp for input values
• process.jsp for dividing the two numbers and displaying the result
• error.jsp for displaying the exception
1) web.xml file if you want to handle any exception
<web-app>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>
</web-app>

Note: This approach is better if you want to handle any exception. If you know any specific error code
and you want to handle that exception, specify the error-code element instead of exception-type as
given below:

2) web.xml file if you want to handle the exception for a specific error code
<web-app>
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
</web-app>
Using try and catch Block
• In JSP, we can also handle the exception by using try and catch block.
• It works on same page instead of firing an error page.
Example : Using try & catch block in JSP page for exception handling

<%
try{
int arr[] = {9,8,7,6,5,4,3};
int num = arr[10];
out.println("11th element of arr"+num);
}catch (Exception exp){
out.println("Cannot find the given index:
" +exp);
}
%>
Action Element in JSP

• There are many JSP action tags or elements.


• Each JSP action tag is used to perform some specific tasks.
• The action tags are used to control the flow between pages and to use Java Bean.
Following are the JSP action tags:
Action tags Description
<jsp:include> Includes a file at the time when the page is requested.

<jsp:useBean> Finds the object of Java bean from a given scope or creates a new object.
<jsp:setProperty> Sets the property of a JavaBean object.

<jsp:getProperty> Prints the property of the Java bean object.

<jsp:forward> Forwards the request and response to another resource.

<jsp:plugin> It is used when there is a need of a plugin to run a Bean class.


<jsp:param> Sets the parameter value to the request. It is used in forward and include mostly.
<jsp:fallback> Supplies alternate text if Java applet is unavailable on the client.
<jsp:element> Defines XML element directly.
jsp:forward action tag
• The jsp:forward action tag is used to forward the request to another resource it may be jsp, html or another
resource.
• The page’s URL must be either relative to the current JSP page or relative to the web application’s context
path (URL starts with a slash: /).
• The JSP forward action effectively terminates the execution of the current JSP page, so the forwarding should
be used based on some dynamic conditions. For example: forward to an error page if an exception occurred or
forward to a login page if the user has not logged in.
• The forwarding happens on the server side which means that the browser is not notified, i.e. the URL in
address bar does not get changed.
• The page’s URL can be a runtime expression that evaluates to a String which is a relative URL.
• The JSP/Servlet container will throw an HTTP 404 error if the forwarded page could not be found.
• Syntax of jsp:forward action tag without parameter
<jsp:forward page="relativeURL | <%= expression %>" />
• Syntax of jsp:forward action tag with parameter
<jsp:forward page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue | <%=expression%>" />
</jsp:forward>
JSP forward action Examples
Forward the request to a page which is relative to the current page:
<jsp:forward page="login.jsp" />
<jsp:forward page="some/path/login.jsp" />

Forward the request to a page which is relative to the web application’s context path:
<jsp:forward page="/login.jsp" />
<jsp:forward page="/some/path/login.jsp" />

Passing additional parameters to the forwarded page:


<jsp:forward page="login.jsp" />
<jsp:param name="username" value="Tom"/>
</jsp:forward>
The <jsp:include> Action Tag Syntax:
• The <jsp:include> standard action is used to include resource into the current JSP page at request time.
• The included resource can be static (HTMP page) or dynamic (JSP page or servlet) and must be relative to
the including JSP page.
For example:
<jsp:include page="content.jsp" />

Syntax of JSP include action


The complete syntax of the <jsp:include> standard action is as follows:
<jsp:include page="relative URL" flush="true|false"/>
or:
<jsp:include page=”urlSpec” flush="true|false">
<jsp:param .... />
</jsp:include>
The latter syntax specifies additional parameters passed to the included page using the
<jsp:param> standard action:
<jsp:param name="name" value="value" />
Attributes of JSP include action
Attribute Required Description
name
page Yes URL of the included page which is interpreted as relative to the current JSP page. The
included resource can be static like HTML or dynamic like JSP and Servlet.
flush Optional If set to true, the servlet container will flush the output buffer prior to the inclusion (if
the page output is buffered). Default is false.

Rules & Behaviors of JSP include action


The inclusion happens at runtime. When the servlet container encounters a <jsp:include> action, it requests the
included page then adds the response into the current JSP page, where the <jsp:include> action is declared. The
following picture explains the inclusion process:
JSP include action Examples
Include a static HTML page (relative to the web application’s context path):
<jsp:include page="/header.html" />
<jsp:include page="/some/path/header.html" />

Include a JSP page (relative to the current JSP page):


<jsp:include page="header.jsp" />
<jsp:include page="some/path/header.jsp" />

Include a servlet:
<jsp:include page="/TestServlet" />
Here, response of the servlet at the URL /TestServlet will be included to the current JSP page.

Flush the output buffer before including:


<jsp:include page="footer.jsp" flush="true"/>

Passing additional parameters:


<jsp:include page="header.jsp" >
<jsp:param name="language" value="english" />
<jsp:param name="country" value="USA" />
</jsp:include>
JavaBean
• A JavaBean is a Java class that should follow the following conventions:
• It should have a no-arg constructor.
• It should be Serializable.
• It should provide methods to set and get the values of the properties, known as getter and
setter methods.

Why use JavaBean?


• JavaBean is a reusable software component.
• A bean encapsulates many objects into one object so that we can access this object from multiple
places.
• Moreover, it provides easy maintenance.
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){
this.id=id;
}
public int getId(){
return id;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
}
How to access the JavaBean class?
To access the JavaBean class, we should use getter and setter methods.
package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName(“PSIT");//setting value to the object
System.out.println(e.getName());
}
}
jsp:useBean action tag
▪ The jsp:useBean action tag is used to locate or instantiate a bean class.
▪ If bean object of the Bean class is already created, it doesn't create the bean depending on
the scope.
▪ But if object of bean is not created, it instantiates the bean.
Syntax of jsp:useBean action tag
<jsp:useBean id= "instanceName" scope= "page | request | session | application"
class= "packageName.className" type= "packageName.className"
beanName="packageName.className | <%= expression >" >
</jsp:useBean>
Attributes and Usage of jsp:useBean action tag
1.id: is used to identify the bean in the specified scope. It creates the object of the bean class and
instantiates it. If the object is already created then id attribute will instantiate that object..
2.scope: represents the scope of the bean. It may be page, request, session or application. The
default scope is page.
o page: specifies that you can use this bean within the JSP page. The default scope is page.
o request: specifies that you can use this bean from any JSP page that processes the same
request. It has wider scope than page.
o session: specifies that you can use this bean from any JSP page in the same session whether
processes the same request or not. It has wider scope than request.
o application: specifies that you can use this bean from any JSP page in the same application.
It has wider scope than session.
3.class: instantiates the specified bean class (i.e. creates an object of the bean class) but it must
have no-arg or no constructor and must not be abstract.
4.type: provides the bean a data type if the bean already exists in the scope. It is mainly used with
class or beanName attribute. If you use it without class or beanName, no bean is instantiated.
5.beanName: instantiates the bean using the java.beans.Beans.instantiate() method.
Simple example of jsp:useBean action tag
Calculator.java (a simple Bean class)
package beans;
public class Calculator{

public int cube(int n){


return n*n*n;
}
}

index.jsp file

<jsp:useBean id="obj" class=“beans.Calculator"/>


<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>
JSP Custom Tags
▪ JSP Custom tags are simply called user-defined tags.

▪ When a JSP is translated into a servlet, these tags get converted to a class.

▪ They are called tag handlers as they do action on an object.

▪ These actions get invoked by the web container at the time of execution of servlet.

▪ To create these tags, we need to extend and SimpleTagSupport, map TLD(Tag Library
Descriptor), override doTag().

▪ These tags can be created so that the functionality of JSP can be extended. They allow
the encapsulation of functionality.
Advantages of Custom Tags in JSP
• Portable – Once declared in the Tag Library, these tags can be used anywhere.
• Simple – They are simple and convenient to use.
• Expressive – It provides a wide range of functionalities, scripting elements to the page
authors.
• Usable from different scripting languages – This functionality can extend to other
scripting languages.
• No need for scriptlet tag – Once we create a custom tag, we don’t need scriptlet tag.
Though it is a bad approach in JSP.
• Reusable – We can use the similar business logic over and over again.
• Separation of business logic from JSP – For easy maintenance, Custom tags separate
business logic and JSP.
Create the Tag handler class
• To create the Tag Handler, we are inheriting the TagSupport class and overriding doStartTag().
• To write data for the jsp, we need to use the JspWriter class.
• The PageContext class provides getOut() method that returns the instance of JspWriter class. TagSupport
class provides instance of pageContext bydefault.
package tags;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class MyTagHandler extends SimpleTagSupport{
public int doStartTag() throws JspException {
JspWriter out=pageContext.getOut();//returns the instance of JspWriter
try{
out.print(“Custom Tags");//printing message using JspWriter
}catch(Exception e){
System.out.println(e);
}
return SKIP_BODY;//will not evaluate the body content of the tag
}
}
Create the TLD file
Tag Library Descriptor (TLD) file contains information of tag and Tag Hander classes. It must be contained inside
the WEB-INF directory.
File: mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>

<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>http://tomcat.apache.org/example-taglib</uri>

<tag>
<name>msg</name>
<tag-class>tagsMyTagHandler</tag-class>
</tag>
</taglib>
Create the JSP file

It uses taglib directive to use the tags defined in the tld file.
File: index.jsp

<%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>


The message is: <m:msg/>

You might also like