Unit 6 - Servlets and Java Server Pages (JSP)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 111

CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 1


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Servlets
Servlet is one of the server-side programming language which runs on Java enabled server. It is
used to develop web-based applications. As it is built on Java platform, servlet is fully compatible
with Java classes and interfaces. Let’s see what are servlets, Java servlets architecture and
advantages of servlets in detail.

Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common
Gateway Interface) scripting language was common as a server-side programming language.
There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.

What is a Servlet?
Servlet can be described in many ways, depending on the context.
• Servlet is a technology which is used to create a web application.
• Servlet is an API that provides many interfaces and classes including documentation.
• Servlet is an interface that must be implemented for creating any Servlet.
• Servlet is a class that extends the capabilities of the servers and responds to the incoming
requests. It can respond to any requests.
• Servlet is a web component that is deployed on the server to create a dynamic web page.

COMPILED BY ER. SANTOSH SHRESTHA 2


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Step 1 : Client i.e. web browser sends the request to the web server.

Step 2 : Web server receives the request and sends it to the servlet container. Servlet container is
also called web container or servlet engine. It is responsible for handling the life of a servlet.

Step 3 : Servlet container understands the request’s URL and calls the particular servlet.
Actually, it creates a thread for execution of that servlet. If there are multiple requests for the
same servlet, then for each request, one thread will be created.

COMPILED BY ER. SANTOSH SHRESTHA 3


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Step 4 : Servlet processes the request object and prepares response object after interacting with
the database or performing any other operations and sends the response object back to the web
server.

Step 5 : Then web server sends the response back to the client.

What is a web application?


A web application is an application accessible from the web. A web application is composed of
web components like Servlet, JSP, Filter, etc. and other elements such as HTML, CSS, and

COMPILED BY ER. SANTOSH SHRESTHA 4


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

JavaScript. The web components typically execute in Web Server and respond to the HTTP
request.

Web browser
A web browser is a program which acts as an interface between user and web application
e.g. Internet Explorer, Chrome, Safari, Mozilla firefox etc.

In the context of a Web application, the client/server model is important because Java code can
run in two places: on the client or on the server. There are trade-offs to both approaches. Server-
based programs have easy access to information that resides on the server, such as customer orders
or inventory data. Because all of the computation is done on the server and results are transmitted
to the client as HTML, a client does not need a powerful computer to run a server-based program.
On the other hand, a client-based program may require a more powerful client computer, because
all computation is performed locally. However, richer interaction is possible, because the client
program has access to local resources, such as the graphics display (e.g., perhaps using Swing) or
the operating system. Many systems today are constructed using code that runs on both the client
and the server to reap the benefit of both approaches.

Web applications built with Java include Java applets, Java servlets, and Java Server Pages
(JSP). Java applets run on the client computer. JavaScript, which is a different language than Java
despite its similar name, also runs on the client computer as part of the Web browser. Java servlets
and Java Server Pages run on the server. Java Server pages which are a dynamic version of Java
servlets. Servlets must be compiled before they can run, just like a normal Java program. In
contrast, JSP code is embedded with the corresponding HTML and is compiled “on the fly” into a
servlet when the page is requested. This flexibility can make it easier to develop Web applications
using JSP than with Java servlets. The following fig1, fig2 and fig3 shows that the running a Java
applet, Java Servlet and JSP program.

COMPILED BY ER. SANTOSH SHRESTHA 5


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Figure 1: Running a Java Applet

Figure 2: Running a Java Servlet

COMPILED BY ER. SANTOSH SHRESTHA 6


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Figure 3: Running a Java Server Page (JSP) Program

CGI (Common 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.

Disadvantages of CGI
There are many problems in CGI technology:
COMPILED BY ER. SANTOSH SHRESTHA 7
CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

1. If the number of clients increases, it takes more time for sending the response.
2. For each request, it starts a process, and the web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.

Advantages of Servlet

There are many advantages of Servlet over CGI. The web container creates threads for handling
the multiple requests to the Servlet. Threads have many benefits over the Processes such as they
share a common memory area, lightweight, cost of communication between the threads are low.
The advantages of Servlet are as follows:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection, etc.
4. Secure: because it uses java language.

Servlet API
• javax.servlet and javax.servlet.http packages contains the classes and interfaces
for servlet API. These packages are the standard part of Java’s enterprise edition.
• javax.servlet contains a number of classes and interfaces which are mainly used
by servlet container.
• javax.servlet.http contains a number of classes and interfaces which are mainly
used by http protocol.

COMPILED BY ER. SANTOSH SHRESTHA 8


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

HTTP Servlet
If you creating Http Servlet you must extend javax.servlet.http.HttpServlet class, which is an
abstract class. Unlike Generic Servlet, the HTTP Servlet doesn’t override the service() method.
Instead it overrides one or more of the following methods. It must override at least one method
from the list below:
• doGet() – This method is called by servlet service method to handle the HTTP GET request
from client. The Get method is used for getting information from the server
• doPost() – Used for posting information to the Server
• doPut() – This method is similar to doPost method but unlike doPost method where we
send information to the server, this method sends file to the server, this is similar to the
FTP operation from client to server
• doDelete() – allows a client to delete a document, webpage or information from the server
• init() and destroy() – Used for managing resources that are held for the life of the servlet
• getServletInfo() – Returns information about the servlet, such as author, version, and
copyright.
In Http Servlet there is no need to override the service() method as this method dispatches the Http
Requests to the correct method handler, for example if it receives HTTP GET Request it dispatches
the request to the doGet() method.

COMPILED BY ER. SANTOSH SHRESTHA 9


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Interfaces in javax.servlet package


There are many interfaces in javax.servlet package. They are as follows:

1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener

Classes in javax.servlet package


There are many classes in javax.servlet package. They are as follows:

1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent

COMPILED BY ER. SANTOSH SHRESTHA 10


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

10. ServletException
11. UnavailableException

Interfaces in javax.servlet.http package


There are many interfaces in javax.servlet.http package. They are as follows:

1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)

Classes in javax.servlet.http package


There are many classes in javax.servlet.http package. They are as follows:

1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)

COMPILED BY ER. SANTOSH SHRESTHA 11


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Environment Setup of a Servlet

To create a Servlet application, at first, we need to follow some steps like installing
Tomcat Server, which gets described below-

1. Creating a Directory Structure

First, we need to create the above directory structure inside a directory named
Apache – Tomcat\webapps directory. We need to keep all HTML, static files,
images under the web application creating a folder. The servlets must be kept in the
class folder. Lastly, the web.xml file should be under the WEB-INF folder.

2. Creating a Servlet

There are three different ways by which we can create a servlet.

a. By implementing the Servlet interface.


b. By extending the GenericServlet class.
c. It is necessary to extend the HTTP servlet class.
A servlet can be mainly formed if we can extend the httpServlet abstract class.
COMPILED BY ER. SANTOSH SHRESTHA 12
CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

3. Compiling the Servlet

For compiling the servlet, a JAR file is required –

a. By setting the classpath.


b. By pasting the jar in JRE/lib/ext folder.
1. Create Deployment Descriptor
Deployment Descriptor (DD) can be defined as an XML file that is used by web-based
servers so that they can run servlets with ease. DD is used for several important
purposes.

a. By mapping the URL to the Servlet class.


b. By initialising parameters.
c. By defining the Error page.
d. By security roles.
e. By declaring tag libraries.

5. Start the Server

To start the Apache Tomcat server, we need to double click on the startup.bat file
under apache-tomcat/bin directory, and it will start working.

6. Starting Tomcat Server for the First Time

To start Tomcat Server for the first time, we need to set JAVA_HOME in the
Environment variable. The following steps are mentioned below.

a. Right Click on My Computer, and we need to go to Properties.

COMPILED BY ER. SANTOSH SHRESTHA 13


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

b. Next, we will go to Advanced Tab, and we need to click on the Environment Variables
button.

COMPILED BY ER. SANTOSH SHRESTHA 14


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

c. Therefore, we will click on the New button and enter JAVA_HOME inside the Variable
name text field and the path of JDK inside the Variable value text field. Then, we need to
save it by clicking, OK.

COMPILED BY ER. SANTOSH SHRESTHA 15


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

7. Running the Servlet Application

When we run the servlet button, it will look like –

After opening the browser, we need to type http:localhost:8080/First/hello

Servlet Request Interface


ServletRequest aims to supply the client with authentic pieces of information about
a servlet that

includes content type, length, parameter values, and many more.

Methods

1. getAttribute(String)

COMPILED BY ER. SANTOSH SHRESTHA 16


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Returns the value of attributes as requested, if attributes have no existence

then returns NULL.

2. getAttributeNames()

It returns the names of the present attributes that are requested by the clients.

3. getCharacterEncoding()

Returns some set of characters.

4. getContentLength()

Returns the requested data entity size.

5. getContentType()

At first, it requests the object’s identity. If not found, it returns a NULL value.

6. getInputStream()

Returns a binary stream of data received by the client and then returns the strings.

7. getParameter(String)

Returns a string of the parameters.

8. getParameterNames()

It returns the parameter names.

9. getParameterValues(String)

COMPILED BY ER. SANTOSH SHRESTHA 17


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

It returns the values of the parameters. They always exist in the form of a string.

10. getProtocol()

It returns the protocol and version in the form <protocol>/<major version>.<minor


version>.

11. getReader()

It returns a buffered reader to read the text in the request body.

12. getRealPath(String)

avoids the virtual path and returns the real path.

13. getRemoteAddr()

It returns the IP address.

14. getRemoteHost()

It returns the completely structured hostname of the agent.

15. getScheme()

It returns the URL used in the request.

16. getServerName()

It returns the hostname of the server.

17. getServerPort()

COMPILED BY ER. SANTOSH SHRESTHA 18


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

It returns the port number.

18. setAttribute(String, Object)

This method accumulates an attribute for any kind of requests.

Servlet Response
ServletResponse invokes an object, and the response of various users is recorded.
The web container is responsible for all these activities. The step to create this is
very much important. The step is to create an object.

Now let us talk aboutServletConfig and ServletContext below in detail.

ServletConfig
a. Web container creates the config object based on the initialisation
parameters.
b. 2. One ServletConfig per Servlet must be present.

Methods

1. Equals(Object)

checks if the current object has equal value with the given object.

2. GetHashCode()

Works as the default hash function.

3. GetType()

Returns the Type of the current instance.

COMPILED BY ER. SANTOSH SHRESTHA 19


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

4. MemberwiseClone()

If we invoke this object, a shallow copy can be created. It refers to the present
object by default.

5. ToString()

Returns a string, which represents the current object.

Types of Servlets
The two types of servlets can be defined as:

1. Generic Servlets

We refer to the Generic servlets as independent of protocols, and also, it is


required to invoke it by overriding. We can invoke generic servlets in three ways

• HTML File
We can create a very uncomplicated HTML file that can look like
WebContent/index.html.

• Java Class File


A generic servlet can be created by extending the GenericServlet class. If we can
create a simple new class file, then we can rename it as generic. The file path
looks like:/ javaResouces/src/default package/generic.java.

• XML File
We can find this file in the path WebContent/WEB-INF/web.xml. We can
map the servlet with a specific URL.

2. HTTP servlet

COMPILED BY ER. SANTOSH SHRESTHA 20


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

This type of servlets is nothing but an extension of Servlet classes. Though it is


HTTP dependent, it sets some rules which help the web browser and servers to
communicate, and the HTTP servlet can also override doGet() or doPost()
methods. Also, it can override both methods.

Life Cycle of a Servlet

The entire life cycle of a Servlet is managed by the Servlet container which uses
the javax.servlet.Servlet interface to understand the Servlet object and manage it. So, before
creating a Servlet object, let’s first understand the life cycle of the Servlet object which is actually
understanding how the Servlet container manages the Servlet object.
Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through four stages,
• Loading a Servlet.
• Initializing the Servlet.
• Request handling.
• Destroying the Servlet.
Let’s look at each of these stages in details:
1. Loading a Servlet: The first stage of the Servlet lifecycle involves loading and initializing
the Servlet by the Servlet container. The Web container or Servlet Container can load the
Servlet at either of the following two stages :
• Initializing the context, on configuring the Servlet with a zero or positive integer
value.
• If the Servlet is not preceding stage, it may delay the loading process until the Web
container determines that this Servlet is needed to service a request.
The Servlet container performs two operations in this stage :
• Loading : Loads the Servlet class.
• Instantiation : Creates an instance of the Servlet. To create a new instance of the
Servlet, the container uses the no-argument constructor.

COMPILED BY ER. SANTOSH SHRESTHA 21


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

2. Initializing a Servlet: After the Servlet is instantiated successfully, the Servlet container
initializes the instantiated Servlet object. The container initializes the Servlet object by
invoking the Servlet.init(ServletConfig) method which accepts ServletConfig object
reference as parameter.
The Servlet container invokes the Servlet.init(ServletConfig) method only once,
immediately after the Servlet.init(ServletConfig) object is instantiated successfully. This
method is used to initialize the resources, such as JDBC datasource.
Now, if the Servlet fails to initialize, then it informs the Servlet container by throwing
the ServletException or UnavailableException.
3. Handling request: After initialization, the Servlet instance is ready to serve the client
requests. The Servlet container performs the following operations when the Servlet
instance is located to service a request :

COMPILED BY ER. SANTOSH SHRESTHA 22


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

• It creates the ServletRequest and ServletResponse objects. In this case, if this is


a HTTP request, then the Web container
creates HttpServletRequest and HttpServletResponse objects which are
subtypes of the ServletRequest and ServletResponse objects respectively.
• After creating the request and response objects it invokes the
Servlet.service(ServletRequest, ServletResponse) method by passing the request
and response objects.
The service() method while processing the request may throw
the ServletException or UnavailableException or IOException.
4. Destroying a Servlet: When a Servlet container decides to destroy the Servlet, it performs
the following operations,
• It allows all the threads currently running in the service method of the Servlet
instance to complete their jobs and get released.
• After currently running threads have completed their jobs, the Servlet container
calls the destroy() method on the Servlet instance.
After the destroy() method is executed, the Servlet container releases all the references of
this Servlet instance so that it becomes eligible for garbage collection.

Servlet Life Cycle Methods


There are three life cycle methods of a Servlet :
• init()
• service()
• destroy()

COMPILED BY ER. SANTOSH SHRESTHA 23


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Let’s look at each of these methods in details:


1. init() method: The Servlet.init() method is called by the Servlet container to indicate that
this Servlet instance is instantiated successfully and is about to put into service.
//init() method
public class MyServlet implements Servlet{
public void init(ServletConfig config) throws ServletException {
//initialization code
}
//rest of code
}
2. service() method: The service() method of the Servlet is invoked to inform the Servlet
about the client requests.
• This method uses ServletRequest object to collect the data requested by the client.
• This method uses ServletResponse object to generate the output content.

COMPILED BY ER. SANTOSH SHRESTHA 24


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

// service() method
public class MyServlet implements Servlet{
public void service(ServletRequest res, ServletResponse res)
throws ServletException, IOException {
// request handling code
}
// rest of code
}
3. destroy() method: The destroy() method runs only once during the lifetime of a Servlet
and signals the end of the Servlet instance.
//destroy() method
public void destroy()
As soon as the destroy() method is activated, the Servlet container releases the Servlet
instance.

Servlet Life Cycle:


Servlet life cycle can be defined as the stages through which the servlet passes from its
creation to its destruction.
The servlet life cycle consists these stages:
• Servlet is borned
• Servlet is initialized
• Servlet is ready to service
• Servlet is servicing
• Servlet is not ready to service
• Servlet is destroyed

Life cycle methods:


Life cycle methods are those methods which are used to control the life cycle of the servlet.
These methods are called in specific order during the servlets’s entire life cycle.
The class Servlet provides the methods to control and supervise the life cycle of servlet.

COMPILED BY ER. SANTOSH SHRESTHA 25


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

There are three life cycle methods in the Servlet interface. There are as follows:
1. init() method :
• A servlet’s life begins here .
• This method is called only once to load the servlet.Since it is called only once in it’s
lifetime,therefore “connected architecture” code is written inside it because we only
want once to get connected with the database.
Now Question Arises is that:-
Q.Why can’t we write connected architecture code inside the constructor, since
constructor also run only once in it’s entire life?
Ans. Suppose if the connection doesn’t get established, then we can throw an
exception from init() and the rest of the steps stop executing. But in the constructor
we can’t use, throw in it’s prototype otherwise it is an error.
• This method receives only one parameter, i.e ServletConfig object.
• This method has the possibility to throw the ServletException.
• Once the servlet is initialized, it is ready to handle the client request.
• The prototype for the init() method:
public void init(ServletConfig con)throws ServletException{ }
where con is ServletConfig object
NOTE:- In programs of servlet,we use non parameterized version of init().
Now, Question Arises is that:-
Q. Why it is recommended to use the non parameterized version of init() instead of
parameterized version as seen above?
Ans. To answer this, we have to go into detail. Think like developers,i.e there must be
some valid reason for this and the answer will blow your mind. Coming to answer:
APPROACH 1
Whenever the lifecycle method of a servlet starts executing,i.e when public void
init(ServletConfig con) throws ServletException gets call then our class public void
init(ServletConfig con) throws ServletException gets called but we have to run the code
which initializes servlet config object which is written inside “HttpServlet” method

COMPILED BY ER. SANTOSH SHRESTHA 26


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

public void init(ServletConfig con) throws ServletException,i.e:


Coding of HttpServlet class be like:
public void init(ServletConfig con) throws ServletException
{
//code to initialise ServletConfig object
init(); /*This HttpServlet has 2 init() one which is parameterized and the other
one is non parameterized.But this non parameterized version of init() has a blank
body. So this call is useless. */
}
Now see the coding of our class
public void init(ServletConfig con) throws ServletException
{
/*Since,our class init() will run first,but to run HttpServlet init() we have used super
keyword.*/
super.init(con);
}
NOTE:- As we can see, total 3 init() calls we have to make.First init() gets called of our
class then of HttpServlet class then non parameterized version of HttpServlet class.
But now, we will achieve the same thing with less number of calls:
APPROACH 2
Coding of HttpServlet parametrized and non parameterized versions of init() will remain
the same. But in our class instead of overriding parameterized version of init(), we
will override non parameterized version of init().
Let’s see the coding of our class non parameterized version of init():
public void init() throws ServletException
{
//database connectivity code
}
NOTE: Since this method public void init() throws ServletException ,we have override
from HttpServlet class whose coding is like:

COMPILED BY ER. SANTOSH SHRESTHA 27


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

public void init() throws ServletException


{
//empty body
}
Since it’s body is blank, therefore it is known as “Helper method” as it is used for
overriding purpose.
Now, as the servlet starts executing its methods, it will call the parameterized version of
init(). Since we have not to override the parameterized version, therefore it will give a
call to the HttpServlet parameterized version of init(). Since coding of a parameterized
version of init() of HttpServlet is as same as above, therefore, from there on it will call
init() (i.e non parameterized version of init). It will give a call to our class non
parameterized version of init() and the code continues.
Now, as you can see, total number of init() calls are 2 which is less than the first
approach. Therefore, execution time is less in 2nd approach and less headache for
CPU for maintaining stack and it’s speed increases as compared to 1st approach.
Therefore, it is highly recommended to override non parameterized version of
init().Although both will run but due to efficiency first approach is rarely used and also in
first approach we have to use super keyword too.Therefore in below mentioned
program,we have override non parameterized version of init().
2. service() method :
• The service() method is the most important method to perform that provides the
connection between client and server.
• The web server calls the service() method to handle requests coming from the
client( web browsers) and to send response back to the client.
• This method determines the type of Http request (GET, POST, PUT, DELETE, etc.)
• This method also calls various other methods such as doGet(), doPost(), doPut(),
doDelete(), etc. as required.
• This method accepts two parameters.
• The prototype for this method:
public void service(ServletRequest req, ServletResponse resp)

COMPILED BY ER. SANTOSH SHRESTHA 28


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

throws ServletException, IOException { }


where
• req is the ServletRequest object which encapsulates the connection from client to server
• resp is the ServletResponse object which encapsulates the connection from server back to
the client
3. destroy() method :
• The destroy() method is called only once.
• It is called at the end of the life cycle of the servlet.
• This method performs various tasks such as closing connection with the database, releasing
memory allocated to the servlet, releasing resources that are allocated to the servlet and other
cleanup activities.
• When this method is called, the garbage collector comes into action.
• The prototype for this method is:
public void destroy() { // Finalization code...}
Below is a sample program to illustrate Servlet in Java:
// Java program to show servlet example
// Importing required Java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class AdvanceJavaConcepts extends HttpServlet
{
private String output;

// Initializing servlet
public void init() throws ServletException
{
output = "Advance Java Concepts";
}

COMPILED BY ER. SANTOSH SHRESTHA 29


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

// Requesting and printing the output


public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println(output);
}

public void destroy()


{
System.out.println("Over");
}
}

COMPILED BY ER. SANTOSH SHRESTHA 30


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Java Servlets are programs that run on a Web or Application server and act as a middle
layer between a requests coming from a Web browser or other HTTP client and databases or
applications on the HTTP server.

Using Servlets, we can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.

Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).

HTTP
• HTTP stands for Hyper Text Transfer Protocol. Following are some of the important
properties of HTTP:

Þ It is a stateless protocol, meaning that every HTTP request is independent of each


other.
Þ It can send data in the request. The server side program reads the data, processes
it and sends the response back. This is the most important feature of HTTP, the
ability to send data to server side program.

• Based on how the data is sent in the request, HTTP requests are categorized into several

types, but the most important and widely used are the GET requests and POST requests.

• A typical HTTP request is identified by something called URI (Uniform Resource

Identifier) as shown below:

http:// <host name>:<port number>/<request details>

GET Request
o GET request is the simplest of all the requests. This type of request is normally used for
accessing server-side static resources such as HTML files, images etc. This doesn’t mean
that GET requests cannot be used for retrieving dynamic resources. To retrieve dynamic
resources, some data must be sent in the request and GET request can send the data by
appending it in the URI itself as shown below:

COMPILED BY ER. SANTOSH SHRESTHA 31


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

http://somedomain.com?uid=John&role=admin

In the above URI, the HTTP request sends two pieces of data in the form of name value
pairs. Each name-value pair must be separated by ‘&’ symbol. The server side program
will then read the data, process it, and send a dynamic response.

o Though GET request is simplest of all, it has some limitations:

Þ All the data in the request is appended to the URI itself making the data visible to
everyone. When secure information need to be sent, GET request is not the solution.
Þ GET requests can only send text data and not the binary data. Therefore in situations
where you need to upload image files to server, GET request cannot be used.

POST Request

• POST request is normally used for accessing dynamic resources.


• POST requests are used when we need to send large amounts of data to the server.
• Moreover, the data in the POST request is hidden behind the scenes therefore making

data transmittal more secure.

• In most of the real world applications, all the HTTP requests are sent as POST requests.

Server Side of the Web Application

The server- side is the heart of any web application as it comprises of the following:

Þ Static resources like HTML files, XML files, Images etc


Þ Server programs for processing the HTTP requests
Þ A runtime that executes the server side programs
Þ A deployment tool for deploying the programs in the server

In order to meet the above requirements, J2EE offers the following:

Þ Servlet and JSP technology to build server side programs


Þ Web Container for hosting the server side programs.
Þ Deployment descriptor which is an XML file used to configure the web
application.

COMPILED BY ER. SANTOSH SHRESTHA 32


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Web Container
• A Web container is the heart of Java based web application which is a sophisticated
program that hosts the server side programs like Servlets.
• Once the Servlet programs are deployed in this container, the container is ready to
receive HTTP requests and delegate them to the programs that run inside the container.
These programs then process the requests and generate the responses.
• Also a single web container can host several web applications.
• Look at the following figure that shows how a typical web container looks

Figure : A typical web container

There are several J2EE Web Containers available in the market. One of the most notable one is
the Apache’s Tomcat container which is available for free of cost.

COMPILED BY ER. SANTOSH SHRESTHA 33


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Structure of a Web Application

For the web container to run the web application, the web application must follow a standard
directory structure within the container. Let’s say we want to build a web application named
myweb. The directory structure for this application must be as shown below:

Where webapps is a standard directory within the web container (Tomcat installation directory).
It is from this directory, you need to start creating the directory structure. Following table lists
the purpose of each directory:

All the static resources namely html files, image files can be stored directly under myweb
directory. With the above directory structure, all the components within myweb application
should be accessed with the URL starting with:

http://localhost:8080/myweb/

If you want to create another web application like mywebproject, you must again create the same
directory structure with mywebproject as the root directory and should access the components
using the URL starting with:

http://localhost:8080/mywebproject/

COMPILED BY ER. SANTOSH SHRESTHA 34


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 35


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 36


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 37


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 38


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 39


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 40


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 41


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 42


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 43


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 44


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 45


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 46


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 47


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 48


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 49


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

The form data will be sent in the HTTP request object as name value pairs as shown below:

http://localhost:8080/myweb/SomeServlet?name=John&age=20

The servlet then reads the above request data using the HttpServletRequest object as shown
below:

String fn = request.getParameter(“name”);
String age = request.getParameter(“age”);

fn will now have John and age will have 20. The servlet can do whatever it want with the data,
and send a confirmation message back.

COMPILED BY ER. SANTOSH SHRESTHA 50


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 51


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

//File: SimpleInterestFindingServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SimpleInterestFindingServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//reading the values
String principle =request.getParameter("principle");
String time=request.getParameter("time");
String rate=request.getParameter("rate");
//parsing the string values to double
double t = Double.parseDouble(time);
double p = Double.parseDouble(principle);
double r = Double.parseDouble(rate);
// declaring variable to hold the result
double si;
//computing simple interest
si = (p*t*r)/100;

COMPILED BY ER. SANTOSH SHRESTHA 52


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

//to send response


out.println("<h3>Simple Interest = "+si+ "</h3>");
}}
------------------------------
// Inside web.xml
...
<servlet>
<servlet-name>SimpleInterestFindingServlet</servlet-
name>
<servlet-
class>someservlets.SimpleInterestFindingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SimpleInterestFindingServlet</servlet-
name>
<url-pattern>/findsi</url-pattern>
</servlet-mapping>
...
Output:

COMPILED BY ER. SANTOSH SHRESTHA 53


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 54


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Example: Reading the values from html form and storing in a table of a database

//File: simpleform.html <html>

<head> <title>Simple Form</title> </head>


<body>
<h3>Please fill in the following details and submit it</h3>
<form action="formprocessing" method="POST">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"/>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age"/>
</tr>
<tr>
<td>Address </td>
<td><input type="text" name="address"/>

</tr>

<tr>
<td> <br/><br/></td>
<td><br/><br/><input type="submit" value="Submit"/>
</tr>
</table>
</form>
</body>
</html>

COMPILED BY ER. SANTOSH SHRESTHA 55


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

//File: FormProcessingServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FormProcessingServlet extends HttpServlet {
String driverName;
String dbURL;
final String DB_USERNAME="root";
final String DB_PASSWORD="";
@Override
public void init(ServletConfig config) throws
ServletException {
// This method is called before the following methods are called
//and gets called only ONCE. This is like a
// constructor. We do all the initialization here.
driverName = config.getInitParameter("driver");
dbURL = config.getInitParameter("URL");
}

@Override

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

COMPILED BY ER. SANTOSH SHRESTHA 56


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String responseMessage;
// Reading the form data
String name = request.getParameter("name");
String a = request.getParameter("age");
String addr = request.getParameter("address");
try{
//converting age value into int
int age = Integer.parseInt(a);
//calling method which conneccts to db and inserts values
int status=connectAndInsert(name,age,addr);
if (status!=-1)
responseMessage = "Congratulations! the form is successfully submitted";

else

responseMessage = "Sorry! something went wrong. Please try again"; }


catch(Exception e){
responseMessage= "Error !!! " + e;
}
// Sending the response
out.println("<h1>" + responseMessage + "</h1>");
}
//method to handle db related works...
private int connectAndInsert(String name, int age, String
addr)throws Exception{
Class.forName(driverName);
Connection con;
con = DriverManager.getConnection(dbURL, DB_USERNAME,DB_PASSWORD);
String queryToFire = "INSERT INTO personalrecord VALUES(\'"+name+"\',"+age+",
\'"+addr+"\')";
COMPILED BY ER. SANTOSH SHRESTHA 57
CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Statement st;
st = con.createStatement();
int n;
n=st.executeUpdate(queryToFire);
st.close();
con.close();
return n;

}}

-------------------------------------------------------------

File: web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

<servlet>

<servlet-name>FormProcessingServlet</servlet-name>
<servlet-
class>someservlets.FormProcessingServlet</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>
<init-param>
<param-name>URL</param-name>
<param-
value>jdbc:mysql://localhost:3306/java2lab</param-value>

COMPILED BY ER. SANTOSH SHRESTHA 58


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FormProcessingServlet</servlet-name>
<url-pattern>/formprocessing</url-pattern>
</servlet-mapping>
</web-app>

Outputs:

COMPILED BY ER. SANTOSH SHRESTHA 59


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Session Management (Imp)


The examples we saw until now just deal with one servlet. However, a typical web application
comprises of several servlets that require collaborating with each other to give a complete
response. For instance, if you go online to purchase a book, you need to go through multiple
pages like search page, shopping page, billing page etc before you can complete the transaction.
In situations like this, it is important that one servlet shares information or data with other
servlet.

In web application terminology we call the shared data or information as state. Having state is
just not sufficient. Someone must be able to pass this state from one servlet to other servlet so
that they can share the data. So, who does this state propagation? Can HTTP do this? No,
because HTTP is a stateless protocol which means it cannot propagate the state. So, is there
anyone to help us out here to make the state available to all the servlets? Yes, there is one guy
who is always there for our rescue and it’s none other than web container (Tomcat).

HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client
opens a separate connection to the Web server and the server automatically does not keep any
record of previous client request.

A web container provides a common storage area called as session store the state and provides
access to this session to all the servlets within the web application. For instance, servlet A can
create some state (information) and store it in the session. Servlet B can then get hold of the
session and read the state.

COMPILED BY ER. SANTOSH SHRESTHA 60


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

• Session simply means a particular interval of time.


• Session tracking is a way to maintain state (data) of an user. It is also known as session
Management in servlet.

There are following ways to maintain session between web client and web server (i.e. State can
be maintained indirectly) using –

1. Cookies
2. Hidden Form Fields
3. URL Rewriting
4. HttpSession Object

But here we are just focusing on HttpSession Object

Cookies
A webserver can assign a unique session ID as a cookie to each web client and for subsequent
requests from the client they can be recognized using the received cookie.

This may not be an effective way because many time browser does not support a cookie.

Hidden Form Fields


A web server can send a hidden HTML form field along with a unique session ID as follows −

<input type = "hidden" name = "sessionid" value = "12345">


This entry means that, when the form is submitted, the specified name and value are
automatically included in the GET or POST data. Each time when web browser sends request
back, then session_id value can be used to keep the track of different web browsers.

This could be an effective way of keeping track of the session but clicking on a regular (<A
HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot
support general session tracking.

URL Rewriting
You can append some extra data on the end of each URL that identifies the session, and the
server can associate that session identifier with data it has stored about that session.

COMPILED BY ER. SANTOSH SHRESTHA 61


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

For example, with http://tutorialspoint.com/file.htm;sessionid = 12345, the session identifier is


attached as sessionid = 12345 which can be accessed at the web server to identify the client.

URL rewriting is a better way to maintain sessions and it works even when browsers don't
support cookies. The drawback of URL re-writing is that you would have to generate every
URL dynamically to assign a session ID, even in case of a simple static HTML page.

The HttpSession Object


Apart from the above mentioned three ways, servlet provides HttpSession Interface which
provides a way to identify a user across more than one page request or visit to a Web site and to
store information about that user.

The servlet container uses this interface to create a session between an HTTP client and an
HTTP server. The session persists for a specified time period, across more than one connection
or page request from the user.

You would get HttpSession object by calling the public method getSession()of
HttpServletRequest, as below −

HttpSession session = request.getSession();

Since the state (data or information) in the session is user specific, the web container maintains a
separate session for each and every user as shown in the following diagram.

COMPILED BY ER. SANTOSH SHRESTHA 62


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Figure 2: Session Management

If you look at the above figure, every user will have his own session object for storing the state
pertaining to his transaction and all the servlets will have access to the same session. Also notice,
the session objects are present within the container.

Now that we know what a session is, let’s see how a servlet uses the session for sharing the data
across multiple pages in a web application. A servlet can do the following four most important
operations to work with sessions.

(These four operations are also called as Session Management operations)

1. Create the session


2. Store the data in the session
3. Read the data from the session
4. Destroy the session or invalidate the session.

Creating a Session
The servlet API provides us with a class called HttpSession to work with sessions. To create a
session, we do the following:

HttpSession session = request.getSession(true);

COMPILED BY ER. SANTOSH SHRESTHA 63


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

The above method returns a new session object if one is not present, otherwise it returns the old
session object that is already created before.

Storing the data in Session


Data in session is stored as key-value pair just like in HashMap or Hashtable. The value can be
any Java object and the key is usually a String.

To store the data we use the setAttribute() method as shown below:

session.setAttribute(“price”,new Double(“12.45”));

Reading the data from the Session

To read the data, we need to use the getAttribute() method by passing in the key as shown below
which then returns the value object:

Double d = (Double)session.getAttribute(“price”);

Notice that we need to do proper casting here. Since we stored Double object, we need to cast it
again as Double while reading it.

Destroying the Session

A session is usually destroyed by the last page or servlet in the web application. A session is
destroyed by invoking the invalidate() method as shown below:

session.invaliadte()

COMPILED BY ER. SANTOSH SHRESTHA 64


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 65


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Request Dispatching
• Request dispatching is the ability of one servlet to dispatch or delegate the request to another
servlet for processing.
• In simple words, let's say we have a servlet A which doesn't know how to completely process
the request. Therefore, after partially processing the request, it should forward the request to
another servlet B. This servlet then does the rest of the processing and sends the final response
back to the browser.
• The class used for dispatching requests is the RequestDispatcher interface in Servlet API. This
interface has two methods namely forward() and include().

COMPILED BY ER. SANTOSH SHRESTHA 66


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

• The getRequestDispatcher() method of ServletRequest interface returns the object of


RequestDispatcher.

Syntax:
public RequestDispatcher getRequestDispatcher(String resource);

Example:
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
//servlet2 is the url-pattern of a servlet
rd.forward(request, response); //method may be include or forward
The forward() method
This method is used for forwarding request from one servlet to another. Consider two servlets A
and B. Using this method, A gets the request, which then forwards the request to B, B processes
the request and sends the response to the browser. This method takes HttpServletRequest and
HttpServletResponse as parameters.
The include() method
With this method, one servlet can include the response of other servlet. The first servlet will then
send the combined response back to the browser. This method also takes HttpServletRequest
and HttpServletResponse as parameters.
Following two figures demonstrate dispatching using forward() and include() methods

COMPILED BY ER. SANTOSH SHRESTHA 67


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Note:

public void forward(HttpServletRequest request, HttpServletResponse response):

It forwards the request from one servlet to another resource (such as servlet, JSP, HTML file).
public void include(HttpServletRequest request, HttpServletResponse response): It includes the
content of the resource(such as servlet, JSP, HTML file) in the response.

forward() vs include() method

To understand the difference between these two methods, let’s take an example: Suppose you
have two pages X and Y. In page X you have an include tag, this means that the control will be
in the page X till it encounters include tag, after that the control will be transferred to page Y. At
the end of the processing of page Y, the control will return back to the page X starting just after
the include tag and remain in X till the end.
In this case the final response to the client will be send by page X.

Now, we are taking the same example with forward. We have same pages X and Y. In page X,
we have forward tag. In this case the control will be in page X till it encounters forward, after

COMPILED BY ER. SANTOSH SHRESTHA 68


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

this the control will be transferred to page Y. The main difference here is that the control will not
return back to X, it will be in page Y till the end of it.

In this case the final response to the client will be send by page Y.

COMPILED BY ER. SANTOSH SHRESTHA 69


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Example : Request Dispatching ( RequestDispatcher interface, forward() and


include() methods)
In this example, we are validating the username and password entered by the user. If username is
Learner and password is servlet123, it will forward the request to the WelcomeServlet, otherwise
will show an error message: sorry username or password error!. In this program, we are cheking
for hardcoded information. But you can check it to the database. In this example, we have
created following files:
index.html file: for getting input from the user.
Login.java file: a servlet class for processing the response. If username is Learner and password
is servlet123, it will forward the request to the welcome servlet.
WelcomeServlet.java file: a servlet class for displaying the welcome message.
web.xml file: a deployment descriptor file that contains the information about the servlet.

index.html

COMPILED BY ER. SANTOSH SHRESTHA 70


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

<html>
<head>
<title>RequestDispatching</title>
<h4> Login </h4>
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="LOGIN"/>
</form>
</body>
</html>

//Login.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Login extends HttpServlet {

@Override

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("userName");
String pass=request.getParameter("userPass");
if(name.equals("Learner")&& pass.equals("servlet123")){
COMPILED BY ER. SANTOSH SHRESTHA 71
CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

RequestDispatcher
rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}

else{

out.print("Sorry UserName or Password Error!");


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

} }}

//WelcomeServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WelcomeServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("userName");
out.print("Welcome "+name);

} }

COMPILED BY ER. SANTOSH SHRESTHA 72


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

//web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>someservlets.Login</servlet-class>
</servlet>

<servlet>

<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>someservlets.WelcomeServlet</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>

COMPILED BY ER. SANTOSH SHRESTHA 73


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 74


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Example : Servlet HttpSession Login and Logout getAttribute methods.

In this example, we are creating 3 links: login, logout and profile. User can't go to profile page
until s/he is logged in. If user is logged out, s/he need to login again to visit profile.

In this application, we have created following files.

1. main.html
2. link.html
3. login.html
4. LoginServlet.java
5. LogoutServlet.java
6. ProfileServlet.java
7. web.xml

//main.html

<!DOCTYPE html>
<html>
<head><title>MainPage</title></head>
<body>
<div align = "center">
<h1>Login App using HttpSession</h1>
<hr/>
<h2>
<a href="login.html">Login</a>|
<a href="LogoutServlet">Logout</a>|
<a href="ProfileServlet">Profile</a>

</h2>

<br/><hr/>
</div>
</body>
</html>

//login.html
<!DOCTYPE html>
<html><head><title>LoginPage</title></head>
<body>
<div align ="center"><h2> Login </h2>
<form action="LoginServlet" method="post">

COMPILED BY ER. SANTOSH SHRESTHA 75


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

User Name:<input type="text" name="name">


<br/><br/>
Password:<input type="password" name="password">
<br/><br/>
<input type="submit" value="login">
</form>
</div>
</body>

</html>

//link.html
<!DOCTYPE html>
<html>
<head><title>Links</title></head>
<body>
<div align ="center">
<h2> <a href="login.html">Login</a> |
<a href="LogoutServlet">Logout</a> |
<a href="ProfileServlet">Profile</a>
</h2><hr/> <hr/>
</div>
</body>

</html>

//LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {

@Override

public void doPost(HttpServletRequest request,


HttpServletResponse response)throws ServletException,
IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request,
response);

COMPILED BY ER. SANTOSH SHRESTHA 76


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

String name=request.getParameter("name");
String password=request.getParameter("password");
if(password.equals("admin123")){
out.print("Welcome, "+name);
HttpSession session=request.getSession();
session.setAttribute("name",name);

} else{

out.print("<h3><font color ='red'>Sorry, username or


password error!</font><h3>");
request.getRequestDispatcher("login.html").include(request,
response);

out.close();
}

} ---------------------------------------------------
//LogoutServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LogoutServlet extends HttpServlet {

@Override

public void doGet(HttpServletRequest request,HttpServletResponse


response)throws ServletException,IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request,
response);
COMPILED BY ER. SANTOSH SHRESTHA 77
CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

} }

HttpSession session=request.getSession(false);
if(session==null){
out.print("You are not logged in yet!");
}

else {

session.invalidate();
out.print("You are successfully logged out!");
}
out.close();
}
}
//ProfileServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ProfileServlet extends HttpServlet {

@Override

public void doGet(HttpServletRequest request,HttpServletResponse


response)throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request,
response);

COMPILED BY ER. SANTOSH SHRESTHA 78


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

HttpSession session=request.getSession(false);
if(session!=null){
String name=(String)session.getAttribute("name");
out.print("Hello, "+name+" Welcome to Profile <br/> You
are awesome :)");

} else{

out.print("<h3><font color='red'> Please login


first</font></h3>");
request.getRequestDispatcher("login.html").include(request,
response);

out.close();
}

} ----------------------------------------------- //web.xml
<web-app>
<servlet>

<servlet-name>LoginServlet</servlet-name>
<servlet-class>someservlets.LoginServlet</servlet-class>
</servlet>

<servlet>

<servlet-name>LogoutServlet</servlet-name>
<servlet-class>someservlets.LogoutServlet</servlet-
class>
</servlet>
<servlet>
<servlet-name>ProfileServlet</servlet-name>

COMPILED BY ER. SANTOSH SHRESTHA 79


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

<servlet-class>someservlets.ProfileServlet</servlet-
class>

</servlet>

<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/LogoutServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ProfileServlet</servlet-name>
<url-pattern>/ProfileServlet</url-pattern>
</servlet-mapping>
</web-app>
-------------------------------------------------------------

COMPILED BY ER. SANTOSH SHRESTHA 80


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

When Profile is clicked without logging in

When login is clicked

COMPILED BY ER. SANTOSH SHRESTHA 81


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

When incorrect password is entered

When correct password is entered

COMPILED BY ER. SANTOSH SHRESTHA 82


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Clicking on profile after logging in

COMPILED BY ER. SANTOSH SHRESTHA 83


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

After clicking on logout

COMPILED BY ER. SANTOSH SHRESTHA 84


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

JSP Programming
• JSP is another J2EE technology for building web applications using Java.
• JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than servlet
such as expression language, JSTL, etc.
• Java Server Pages (JSP) is a technology which is used to develop web pages by
inserting Java code into the HTML pages by making special JSP tags.
• JSP technology is built on top of servlet technology. This is why we can call JSP as an
abstraction over servlet. What does abstraction mean? In simple terms, abstraction is a
simplified fine grained layer over a slightly more complex layer that makes the
development faster and easier. More the abstraction, more the simplicity.
• JSP technology is used to create dynamic web applications. JSP pages are easier to
maintain than a Servlet. JSP pages are opposite of Servlets as a servlet adds HTML code
inside Java code, while JSP adds Java code inside HTML using JSP tags. Everything
a Servlet can do, a JSP page can also do it.

JSP Basics
A typical JSP page very much looks like html page with all the html markup except that you also
see Java code in it. So, in essence,

HTML + Java = JSP

Therefore, JSP content is a mixed content, with a mixture of HTML and Java. If this is the case,
one question arises. Can we save this mixed content in a file with “.html” extension? You guessed
it right. No we can’t, because the html formatter will also treat the Java code as plain text which is
not what we want. We want the Java code to be executed and display the dynamic content in the
page. For this to happen, we need to use a different extension which is the “.jsp” extension. Good.
To summarize, a html file will only have html markup, and a jsp file will have both html
markup and Java code. Point to be noted.

COMPILED BY ER. SANTOSH SHRESTHA 85


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Now, look at the following figure:

Figure 1: HTML and JSP Requests

• When the browser requests for html file, the web container simply responds with a html
response without any processing.
• However, when the browser sends a JSP page request, the web container assumes that the
JSP page might include Java code, and translates the page into a Servlet. The servlet then
processes the Java code, and returns the complete html response including the dynamic
content generated by the Java code.
• For a web container to translate JSP, it needs to identify from the JSP page, as to which is
HTML markup and which is Java code. According to J2EE specification, a JSP page must
use special symbols as placeholders for Java code. The web container instead of scratching
its head to identify Java code, simply uses the special symbols to identify it. This is a
contract between JSP and the Web container.
• Let’s understand what these special symbols are. In JSP, we use four different types of
placeholders for Java code. Following table shows these placeholders along with how the
web container translates the Java code with them.

COMPILED BY ER. SANTOSH SHRESTHA 86


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

To better understand the above four place holders, let’s take a sample JSP page and see how the
web container translates it into a Servlet. See the following JSP and Servlet code snippets.

COMPILED BY ER. SANTOSH SHRESTHA 87


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 88


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Lifecycle of JSP

A JSP page is converted into Servlet in order to service requests. The translation of a JSP page to
a Servlet is called Lifecycle of JSP. JSP Lifecycle is exactly same as the Servlet Lifecycle, with
one additional first step, which is, translation of JSP code to Servlet code. Following are the JSP
Lifecycle steps:

1. Translation of JSP to Servlet code.


2. Compilation of Servlet to bytecode.
3. Loading Servlet class.
4. Creating servlet instance.
5. Initialization by calling jspInit() method
6. Request Processing by calling _jspService() method
7. Destroying by calling jspDestroy() method

COMPILED BY ER. SANTOSH SHRESTHA 89


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

Figure 2: JSP Life Cycle

Translation – JSP pages doesn’t look like normal java classes, actually JSP container parse
the JSP pages and translate them to generate corresponding servlet source code. If JSP file name
is home.jsp, usually its named as home_jsp.java.

Compilation – If the translation is successful, then container compiles the generated servlet
source file to generate class file.

Class Loading – Once JSP is compiled as servlet class, its lifecycle is similar to servlet and
it gets loaded into memory.

Instance Creation – After JSP class is loaded into memory, its object is instantiated by
the container.

Initialization – The JSP class is then initialized and it transforms from a normal class to
servlet. After initialization, ServletConfig and ServletContext objects become accessible to JSP
class.

Request Processing – For every client request, a new thread is spawned with
ServletRequest and ServletResponse to process and generate the HTML response.

Destroy – Last phase of JSP life cycle where it’s unloaded into memory.

Web Container translates JSP code into a servlet class source (.java) file, then compiles that into
a java servlet class. In the third step, the servlet class bytecode is loaded using classloader. The
Container then creates an instance of that servlet class.

The initialized servlet can now service request. For each request the Web Container call
the _jspService() method. When the Container removes the servlet instance from service, it calls
the jspDestroy() method to perform any required clean up.

COMPILED BY ER. SANTOSH SHRESTHA 90


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

What happens to a JSP when it is translated into Servlet?

Let's see what really happens to JSP code when it is translated into Servlet. The code written
inside <% %> is JSP code.

<html>
<head><title>My First JSP Page</title> </head>
<%
int count = 0;

%>

<body>

Page Count is:


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

</html>

The above JSP page(hello.jsp) becomes this Servlet

public class hello_jsp extends HttpServlet


{
public void _jspService(HttpServletRequest request,
HttpServletResponse response) throws
IOException,ServletException
{
PrintWriter out = response.getWriter();
response.setContenType("text/html");
out.write("<html><body>");
int count=0;
out.write("Page count is:");
out.print(++count);
out.write("</body></html>");

COMPILED BY ER. SANTOSH SHRESTHA 91


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

This is just to explain, what happens internally. As a JSP developer, you do not have to worry
about how a JSP page is converted to a Servlet, as it is done automatically by the web container.

COMPILED BY ER. SANTOSH SHRESTHA 92


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

If the session attribute is set to true, then the page will have access to session.

Ex 3: If a JSP page should forward to a custom error page for any exceptions within the page,
the page directive will be as shown below:

COMPILED BY ER. SANTOSH SHRESTHA 93


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

<%@ page errorPage=”Error.jsp” %>

The web container will then forward the request to Error.jsp if it encounters exceptions within
the page.

Ex 4: If a JSP page should allow itself as an error page for other JSP pages, it should use the
following page attribute:

<%@ page isErrorPage=”true” %>

Instead of defining one attribute per page directive, we can define all the attributes at a time as
shown below:

<%@ page import=”java.util.*” session=”true”


errorPage=”Error.jsp” %>

Example:

//File:PageDirectiveDemo.jsp
<%@ page import="java.util.*" session= 'true'
isErrorPage='false'%>
<HTML>
<HEAD><TITLE>PageDirectiveDemo</TITLE></HEAD>
<BODY>
<h4>Welcome to the world of JSP</h4>
This JSP uses the page directive
</BODY>
</HTML>

COMPILED BY ER. SANTOSH SHRESTHA 94


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

The include directive

This directive is used to include the response of another resource (JSP or html) at the point where
the directive is placed in the current JSP. Its usage is shown below.

<%@ include file=”file_name” %>

Example: File:IncludeDirectiveDemo.jsp <HTML>

<HEAD><TITLE>IncludeDirectiveDemo</TITLE></HEAD>
<BODY>
<h4> This is the response from the current JSP page</h4>
<h3> Following is the response from another JSP </h3>
<hr/>
<%@ include file='/jsps/PageDirectiveDemo.jsp' %>
<hr/>
</BODY>

</HTML>

COMPILED BY ER. SANTOSH SHRESTHA 95


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

The taglib directive

This directive allows the JSP page to use custom tags written in Java. Custom tag definitions are
usually defined in a separate file called as Tag Library Descriptor. For the current JSP to use a
custom tag, it needs to import the tag library file which is why this directive is used. Following is
how taglib directive is used.

<%@ taglib uri=”location_of_definition_file”prefix=”prefix_name”


%>

JSP Declarations

JSP declarations are used to declare global variables and methods that can be used in the entire
JSP page. A declaration block is enclosed within <%! and %> symbols as shown below:

<%!
Variable declarations
Global methods
%>

Example:
<html>
<head><title>JSPDeclarationDemo</title></head>
<body>
<%@ page import = "java.util.Date" %>
<%!
String getGreeting( String name){
Date d = new Date();
return "Namaste " + name + "! It's "+ d + " and how are you
doing today";
}
%>
<h3> This is a JSP Declaration demo. The JSP invokes the

COMPILED BY ER. SANTOSH SHRESTHA 96


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

global method to produce the following


</h3>
<hr/>
<h3> <%= getGreeting("Guys") %>
<hr/>
</body>
</html>

JSP Expressions
Expressions in JSP are used to display the dynamic content in the page. An expression could be a
variable or a method that returns some data or anything that returns a value back. Expressions are
enclosed in <%= and %> as shown below

<%= Java Expression %>


Example
<html>
<head><title> JSP Expression Demo </title> </head>
<body>
<%!
String str="We are students of TU";
int fact(int n){
COMPILED BY ER. SANTOSH SHRESTHA 97
CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

int result;
if(n==0){
return 1;
}
else{
result = n*fact(n-1);
return result;
}

%>

<h2>This is to demonstrate JSP Expressions</h2>

<br/>

<h4>Length of thestring '<%=str%>' is--->


<%=str.length()%>
</h4>
<br/><hr/><br/>
<h4> Factorial of 5 is---> <%=fact(5)%></h4>
</body>
</html>

COMPILED BY ER. SANTOSH SHRESTHA 98


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

JSP Scriptlets

A Scriptlet is a piece of Java code that represents processing logic to generate and display the
dynamic content where ever needed in the page. Scriptlets are enclosedbetween <% and %>
symbols. This is the most commonly used placeholder for Java. code.

This JSP Scripting Element allows you to put in a lot of Java code in your HTML code. This
Java code is processed top to bottom when the page is the processed by the web server. Here the
result of the code isn’t directly combined with the HTML rather you have to use “out.println()”
to show what you want to mix with HTML.

<html>
<head><title>JSP Scriplet Demo</title></head>
<body>
<h2> This is an example using JSP Scriplets</h2>
<br/><hr/><h3>The multiplication table of 7 </h3>
<% for(int i =1; i<=10;i++){
out.print("7 * "+ i+ "= "+7*i+"<br/>");
} %>
<br/><hr/><br/>
<h3> Following is generated by the Loop</h3>
<% for(int i=2;i<=5;i++){
if( i % 2 == 0){
out.print(i + " is an even number <br/>");
}
else{
out.print(i + " is an odd number <br/>");

} } %>

</body>
</html>

COMPILED BY ER. SANTOSH SHRESTHA 99


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 100


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

COMPILED BY ER. SANTOSH SHRESTHA 101


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

showdate.jsp

<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %> </body>
</html>

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.

form1.html

welcome.jsp

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

<h1> <% String name=request.getParameter("uname");


out.print("welcome "+name); %> </h1>

COMPILED BY ER. SANTOSH SHRESTHA 102


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

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
‘wordlover’.

form2.html
<form action="redirect.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

COMPILED BY ER. SANTOSH SHRESTHA 103


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

redirect.jsp
<body>

<%
response.sendRedirect("http://www.wordloverbipin.wordpr
ess.com");

%>
</body>

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.

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.

session implicit object


In JSP, session is an implicit object of type HttpSession.The Java developer can use this object to
set,get or remove attribute or to get session information.

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

In JSP, page scope is the default scope.

COMPILED BY ER. SANTOSH SHRESTHA 104


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

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.It is better to learn it after page
directive.

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;

COMPILED BY ER. SANTOSH SHRESTHA 105


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

JSTL (JSP Standard Tag Library)


The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP development.

Advantage of JSTL

1. Fast Development JSTL provides many tags that simplify the JSP.

COMPILED BY ER. SANTOSH SHRESTHA 106


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

2. Code Reusability We can use the JSTL tags on various pages.


3. No need to use scriptlet tag It avoids the use of scriptlet tag.

JSTL Tags
There JSTL mainly provides five types of tags:

Tag Name Description

Core tags The JSTL core tag provide variable support, URL management, flow control,
etc. The URL for the core tag is http://java.sun.com/jsp/jstl/core. The prefix
of core tag is c.

Function The functions tags provide support for string manipulation and string length.
tags The URL for the functions tags is http://java.sun.com/jsp/jstl/functions and
prefix is fn.

Formatting The Formatting tags provide support for message formatting, number and date
tags formatting, etc. The URL for the Formatting tags
is http://java.sun.com/jsp/jstl/fmt and prefix is fmt.

XML tags The XML tags provide flow control, transformation, etc. The URL for the
XML tags is http://java.sun.com/jsp/jstl/xml and prefix is x.

SQL tags The JSTL SQL tags provide SQL support. The URL for the SQL tags
is http://java.sun.com/jsp/jstl/sql and prefix is sql.

For creating JSTL application, you need to load the jstl.jar file

COMPILED BY ER. SANTOSH SHRESTHA 107


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

JSTL Core Tags


1) c:out
2) c:import
3) c:set
4) c:remove
5) c:catch
6) c:if
7) c:choose
8) c:when
9) c:otherwise
10) c:forEach
11) c:forTokens
12) c:param
13) c:redirect
14) c:url

JSTL Function Tags


1) fn:contains()

2) fn:containsIgnore..

3) fn:endsWith()

4) fn:escapeXml()

5) fn:indexOf()

6) fn:trim()

7) fn:startsWith()

COMPILED BY ER. SANTOSH SHRESTHA 108


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

8) fn:split()

9) fn:toLowerCase()

10) fn:toUpperCase()

11) fn:substring()

12) fn:substringAfter()

13) fn:substringBefore()

14) fn:length()

15) fn:replace()

JSTL Formatting Tags

1) fmt:parseNumber

2) fmt:timeZone

3) fmt:formatNumber

4) fmt:parseDate

5) fmt:bundle

6) fmt:setTimeZone

7) fmt:setBundle

8) fmt:message

9) fmt:formatDate

COMPILED BY ER. SANTOSH SHRESTHA 109


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

JSTL XML Tags

1) x:out

2) x:parse

3) x:set

4) x:choose

5) x:when

6) x:otherwise

7) x:if

8) x:transform

9) x:param

JSTL SQL Tags

1) sql:setDataSource

2) sql:query

3) sql:update

4) sql:param

5) sql:dateParam

6) sql:transaction

COMPILED BY ER. SANTOSH SHRESTHA 110


CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY

JSTL Core Tags (5marks short note)


The JSTL core tag provides variable support, URL management, flow control etc. The syntax used
for including JSTL core library in your JSP is:

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

JSTL Core Tags List

Tags Description

c:out It displays the result of an expression, similar to the way <%=...%> tag
work.

c:import It Retrives relative or an absolute URL and display the contents to


either a String in 'var',a Reader in 'varReader' or the page.

c:set It sets the result of an expression under evaluation in a 'scope' variable.

c:remove It is used for removing the specified scoped variable from a particular
scope.

c:catch It is used for Catches any Throwable exceptions that occurs in the body.

c:if It is conditional tag used for testing the condition and display the body
content only if the expression evaluates is true.

c:choose, c:when, It is the simple conditional tag that includes its body content if the
c:otherwise evaluated condition is true.

c:forEach It is the basic iteration tag. It repeats the nested body content for fixed
number of times or over collection.

c:forTokens It iterates over tokens which is separated by the supplied delimeters.

c:param It adds a parameter in a containing 'import' tag's URL.

c:redirect It redirects the browser to a new URL and supports the context-relative
URLs.

c:url It creates a URL with optional query parameters.

COMPILED BY ER. SANTOSH SHRESTHA 111

You might also like