Module - 4 Servlets
Module - 4 Servlets
Module-4
Introducing servlets
Introducing servlets: Background; The Life Cycle of a Servlet; Using Tomcat for Servlet Development;
A simple Servlet; The Servlet API; The Jakarta. Servlet Package; Reading Servlet Parameter; The
[Link] package; Handling HTTP Requests and Responses; Using Cookies; Session
Tracking. Java Server Pages (JSP); JSP tags, Variables and Objects, Methods, Control statements,
Loops, Request String, Parsing other information, User sessions, Cookies, Session Objects.
Background
Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to
handle the request obtained from the webserver, process the request, produce the response, then send a response
back to the webserver. Properties of Servlets are as follows:
• Servlets work on the server-side.
• Servlets are capable of handling complex requests obtained from the webserver.
Servlet Architecture is can be depicted from the image itself as provided below as follows:
Now let us do discuss eccentric point that why do we need For Server-Side extensions?
The server-side extensions are nothing but the technologies that are used to create dynamic Web pages. Actually, to
provide the facility of dynamic Web pages, Web pages need a container or Web server. To meet this requirement,
independent Web server providers offer some proprietary solutions in the form of APIs(Application Programming
Interface). These APIs allow us to build programs that can run with a Web server. In this case, Java Servlet is also one
of the component APIs of Java Platform Enterprise Edition which sets standards for creating dynamic Web applications
in Java. The Servlet technology is similar to other Web server extensions such as scripts and Hypertext
Preprocessor (PHP). However, Java Servlets are more acceptable since they solve the limitations of CGI such as low
performance and low degree scalability.
What is CGI?
CGI is actually an external application that is written by using any of the programming languages like C or C++ and this
is responsible for processing client requests and generating dynamic content
In CGI application, when a client makes a request to access dynamic Web pages, the Web server performs the following
operations :
• It first locates the requested web page i.e the required CGI application using URL.
• It then creates a new process to service the client’s request.
• Invokes the CGI application within the process and passes the request information to the application. • Collects
the response from the CGI application.
Destroys the process, prepares the HTTP response, and sends it to the client.
So, in CGI server has to create and destroy the process for every request. It’s easy to understand that this approach is
applicable for handling few clients but as the number of clients increases, the workload on the server increases and so
the time is taken to process requests increases.
Servlets can directly communicate with the CGI cannot directly communicate with the
webserver. webserver.
Servlets are less expensive than CGI. CGI is more expensive than Servlets.
Servlets can handle the cookies. CGI cannot handle the cookies.
Initializing a Servlet
When a server loads a servlet, the server runs the servlet's init method. Initialization completes before client
requests are handled and before the servlet is destroyed.
Even though most servlets are run in multi-threaded servers, servlets have no concurrency issues during servlet
initialization. The server calls the init method once, when the server loads the servlet, and will not call the
init method again unless the server is reloading the servlet. The server can not reload a servlet until after the
server has destroyed the servlet by calling the destroy method.
What is Tomcat ?
Tomcat is an open-source web server and servlet. The Apache Software Foundation has developed it. It is
used widely for hosting Java-based applications on the web. It is built on Java technologies and implements
the Java Servlet and JavaServer Pages (JSP) specifications. Tomcat acts as a bridge between web servers and
Java-based applications, facilitating the execution of dynamic content and processing client requests.
Tomcat offers a lightweight and efficient solution for hosting Java web applications. Tomcat is popular for
several reasons. Its scalability is admired by many. Tomcat's robustness is useful. It has great community
support which brings relief to the users. With its modular architecture and adherence to industry standards,
Tomcat enables developers to build and deploy web applications with ease.
Tomcat follows a modular architecture comprising connectors, containers, and the Catalina Servlet container.
This architecture enables Tomcat to efficiently handle client requests and generate responses.
Connectors are in charge of accepting and processing requests that the clients sent to Tomcat. In order to have
a connection with the client, different protocols are used by the connectors. These connectors can be HTTP or
HTTPS. They handle tasks like connection management, request parsing, and data transmission.
Once a request is received, connectors pass it to the appropriate container based on the requested URL.
Containers manage the lifecycle of web applications and execute Java servlets or JSP code to generate
responses. They provide an environment for running web applications, managing resources, and handling
concurrent requests.
The Catalina Servlet container, in particular, is responsible for mapping requests to the appropriate servlet and
managing the servlet's life cycle. It handles the process of generating dynamic content by executing servlet
code and producing the response that is sent back to the client.
Tomcat's modular architecture allows for flexibility and extensibility. Developers can add or customize
components to enhance the functionality of Tomcat according to their specific requirements.
If you are wondering what Tomcat is, it is an open-source web server and servlet. The Apache Software
Foundation has developed it. It is used widely for hosting Java-based applications on the web.
In this comprehensive article, we will explore the various aspects of Tomcat, including its definition,
functionality, installation process on Windows, application deployment, a comparison with other web
servers, and commonly asked questions. You will have a deep understanding of what Tomcat is all about
and what Tomcat is used for when you finish reading this article. You will also understand why Tomcat is
important in the world of web development.
Installing Tomcat on Windows is easy. It is a step-by-step process. Go to the Apache Tomcat website. Once
you go there, check for the recent Tomcat version and download it. You should check what your system needs
before you download it. Also, check the capacity of your system.
When the download is done, the downloaded archive should be extracted. Save the downloaded file in a
directory on your computer.
The JAVA_HOME variable should indicate where the Java Development Kit (JDK) is located on your system.
The CATALINA_HOME variable should point to the Tomcat installation directory. These variables are
crucial for Tomcat to locate the necessary files and execute them properly.
After setting up the environment variables, you can start Tomcat. You can start Tomcat in different ways. It
can be run as a service or the startup scripts that are given can be used. You can also start it in manual mode
from the command line.
When Tomcat starts, it binds to a specific port, typically 8080 by default. By launching a web browser and
going to [Link] you can view the deployed applications and Tomcat server through this port.
First, copy the servlet’s class file into the following directory:
C:\apache-tomcat-10.0.7\webapps\examples\WEB-INF\classes
Next, add the servlet’s name and mapping to the [Link] file in the following directory: C:\apache-tomcat-
10.0.7\webapps\examples\WEB-INF
For instance, assuming the first example, called HelloServlet, you will add the following lines in the section
that defines the servlets:
Next, you will add the following lines to the section that defines the servlet mappings:
A Simple Servlet
To become familiar with the key servlet concepts, we will begin by building and testing a simple servlet. The
basic steps are the following:
1. Create and compile the servlet source code. Then, copy the servlet’s class file to the proper directory, and
add the servlet’s name and mappings to the proper [Link] file.
2. Start Tomcat.
3. Start a web browser and request the servlet. Let us examine each of these steps in detail.
The HelloServlet program we working will demonstrates fundamental servlet concepts, particularly the use of
the [Link] package and the structure of a servlet class
First, note that it imports the [Link] package. This package contains the classes and interfaces
required to build servlets. You will learn more about these later in this chapter. Next, the program defines
HelloServlet as a subclass of GenericServlet. The GenericServlet class provides functionality that simplifies
the creation of a servlet. For example, it provides versions of init( ) and destroy( ), which may be used as is.
You need supply only the service( ) method. Inside HelloServlet, the service( ) method (which is inherited
from GenericServlet) is overridden. This method handles requests from a client. Notice that the first argument
is a ServletRequest object. This enables the servlet to read data that is provided via the client request. The
second argument is a ServletResponse object. This enables the servlet to formulate a response for the client.
The call to setContentType( ) establishes the MIME type of the HTTP response. In this program, the MIME
type is text/html. This indicates that the browser should interpret the content as HTML source code. Next, the
getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to the client as part of the
HTTP response. Then println( ) is used to write some simple HTML source code as the HTTP response.
Compile this source code and place the [Link] file in the proper Tomcat directory as described in
the previous section. Also, add HelloServlet to the [Link] file, as described earlier.
Servlet is faster than CGI as it doesn’t involve the creation of a new process for
every new request received.
Servlets, as written in Java, are platform-independent.
Removes the overhead of creating a new process for each request as Servlet
doesn’t run in a separate process. There is only a single instance that handles all
requests concurrently. This also saves the memory and allows a Servlet to easily
manage the client state.
It is a server-side component, so Servlet inherits the security provided by the
Web server.
The API designed for Java Servlet automatically acquires the advantages of the
Java platforms such as platform-independent and portability. In addition, it
obviously can use the wide range of APIs created on Java platforms such as JDBC
to access the database.
Many Web servers that are suitable for personal use or low-traffic websites are
offered for free or at extremely cheap costs eg. Java servlet. However, the majority
of commercial-grade Web servers are rather expensive, with the notable exception
of Apache, which is free.
[Link]
FilterConfig
A filter configuration object used by a servlet container to pass information to a filter during
initialization.
RequestDispatcher
Defines an object that receives requests from the client and sends them to any resource (such
as a servlet, HTML file, or JSP file) on the server.
Servlet
Defines methods that all servlets must implement.
ServletConfig
A servlet configuration object used by a servlet container to pass information to a servlet
during initialization.
ServletContext
Defines a set of methods that a servlet uses to communicate with its servlet container, for
example, to get the MIME type of a file, dispatch requests, or write to a log file.
ServletContextAttributeEvent
This is the event class for notifications about changes to the attributes of the servlet context of
a web application.
ServletContextEvent
This is the event class for notifications about changes to the servlet context of a web
application.
ServletException
Defines a general exception a servlet can throw when it encounters difficulty.
ServletInputStream
Provides an input stream for reading binary data from a client request, including an
efficient readLine method for reading data one line at a time.
ServletOutputStream
Provides an output stream for sending binary data to the client.
ServletRequest
Defines an object to provide client request information to a servlet.
ServletRequestAttributeEvent
This is the event class for notifications of changes to the attributes of the servlet request in an
application.
ServletRequestEvent
Events of this kind indicate lifecycle events for a ServletRequest
ServletResponse
Defines an object to assist a servlet in sending a response to the client.
GenericServlet
Defines a generic, protocol-independent servlet.
Servlet
Defines methods that all servlets must implement.
ServletConfig
A servlet configuration object used by a servlet container to pass information to a servlet during
initialization.
ServletContext
Defines a set of methods that a servlet uses to communicate with its servlet container, for
example, to get the MIME type of a file, dispatch requests, or write to a log file.
ServletException
Defines a general exception a servlet can throw when it encounters difficulty.
ServletInputStream
Provides an input stream for reading binary data from a client request, including an
efficient readLine method for reading data one line at a time.
ServletRequest
Defines an object to provide client request information to a servlet.
ServletRequestWrapper
Provides a convenient implementation of the ServletRequest interface that can be subclassed by
developers wishing to adapt the request to a Servlet.
ServletResponse
Defines an object to assist a servlet in sending a response to the client.
ServletResponseWrapper
Provides a convenient implementation of the ServletResponse interface that can be subclassed by
developers wishing to adapt the response from a Servlet.
Methods Description
void destroy( ) Called when the servlet is unloaded.
The ServletRequest interface includes methods that allow you to read the names and values of parameters
that are included in a client request. We will develop a servlet that illustrates their use. The example contains
two files. A web page is defined in [Link], and a servlet is defined in
[Link]. The HTML source code for [Link] is shown in the following
listing. It defines a table that contains two labels and two text fields. One of the labels is Employee and the
other is Phone. There is also a submit button. Notice that the action parameter of the form tag specifies a URL.
The URL identifies the servlet to process the HTTP POST request.
<html>
<body>
<center>
<form name="Form1"
method="post"
action="[Link]
servlet/PostParametersServlet">
<table>
<tr>
<td><B>Employee</td>
<td><input type=textbox name="e" size="25" value=""></td>
</tr>
<tr>
<td><B>Phone</td>
<td><input type=textbox name="p" size="25" value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>
The source code for [Link] is shown in the following listing. The service( ) method is
overridden to process client requests. The getParameterNames( ) method returns an enumeration of the
parameter names. These are processed in a loop. You can see that the parameter name and value are output
to the client. The parameter value is obtained via the getParameter( ) method.
import [Link].*;
import [Link].*;
import [Link].*;
public class PostParametersServlet
extends GenericServlet {
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException {
// Get print writer.
PrintWriter pw = [Link]();
// Get enumeration of parameter names.
Enumeration<String> e = [Link]();
// Display parameter names and values.
while([Link]()) {
String pname = [Link]();
[Link](pname + " = ");
String pvalue = [Link](pname);
[Link](pvalue);
}
[Link]();
}
}
Compile the servlet. Next, copy it to the appropriate directory, and update the [Link] file, as previously
described. Then, perform these steps to test this example:
1. Start Tomcat (if it is not already running).
2. Display the web page in a browser.
3. Enter an employee name and phone number in the text fields.
4. Submit the web page.
After following these steps, the browser will display a response that is dynamically generated by the servlet.
The preceding examples have used the classes and interfaces defined in [Link], such as
ServletRequest, ServletResponse, and GenericServlet, to illustrate the basic functionality of servlets.
However, when working with HTTP, you will normally use the interfaces and classes in [Link].
As you will see, its functionality makes it easy to build servlets that work with HTTP requests and responses.
The following table summarizes the interfaces used in this chapter:
Interface Description
The following table summarizes the classes used in this chapter. The most important of these is HttpServlet.
Servlet developers typically extend this class in order to process HTTP requests.
Class Description
Cookies Allows state information to be stored on a client machine.
HttpServlet Provides methods to handle HTTP requests and responses..
The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client. Several constants are
defined. These correspond to the different status codes that can be assigned to an HTTP response. For example, SC_OK
indicates that the HTTP request
Method Description
The HttpSession interface enables a servlet to read and write the state information that is associated with an
HTTP session. All of these methods throw an IllegalStateException if the session has already been invalidated.
Method Description
The HttpServlet class provides specialized methods that handle the various types of HTTP requests. A servlet
developer typically overrides one of these methods. These methods are doDelete( ), doGet( ), doHead( ),
doOptions( ), doPost( ), doPut( ), and doTrace( ). A complete description of the different types of HTTP
requests is beyond the scope of this book. However, the GET and POST requests are commonly used when
handling form input. Therefore, this section presents examples of these cases.
We will develop a servlet that handles an HTTP GET request. The servlet is invoked when a form on a web
page is submitted. The example contains two files. A web page is defined in [Link], and a servlet is
defined in [Link]. The HTML source code for [Link] is shown in the following
listing. It defines a form that contains a select element and a submit button. Notice that the action parameter
of the form tag specifies a URL. The URL identifies a servlet to process the HTTP GET request
<html>
<body>
<center>
<form name="Form1"
action="[Link]
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for [Link] is shown in the following listing. The doGet( ) method is
overridden to process any HTTP GET requests that are sent to this servlet. It uses the getParameter( ) method
of HttpServletRequest to obtain the selection that was made by the user. A response is then formulated.
import [Link].*;
import [Link].*;
import [Link].*;
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = [Link]("color");
[Link]("text/html");
PrintWriter pw = [Link]();
[Link]("<B>The selected color is: ");
[Link](color);
[Link]();
}
Compile the servlet. Next, copy it to the appropriate directory, and update the [Link] file, as previously
described. Then, perform these steps to test this example:
1. Start Tomcat, if it is not already running.
2. Display the web page in a browser.
3. Select a color.
4. Submit the web page.
After completing these steps, the browser will display the response that is dynamically
generated by the servlet.
One other point: Parameters for an HTTP GET request are included as part of the URL that is sent to the
web server. Assume that the user selects the red option and submits the form. The URL sent from the
browser to the server is
[Link]
The characters to the right of the question mark are known as the query string.
Here we will develop a servlet that handles an HTTP POST request. The servlet is invoked when a form on a
web page is submitted. The example contains two files. A web page is defined in [Link], and a
servlet is defined in [Link]. The HTML source code for [Link] is shown in the
following listing. It is identical to [Link] except that the method parameter for the form tag
explicitly specifies that the POST method should be used, and the action parameter for the form tag specifies
a different servlet.
<html>
<body>
<center>
<form name="Form1"
method="post"
action="[Link]
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for [Link] is shown in the following listing. The doPost( ) method is
overridden to process any HTTP POST requests that are sent to this servlet. It uses the getParameter( )
method of HttpServletRequest to obtain the selection that was made by the user. A response is then
formulated.
import [Link].*;
import [Link].*;
import [Link].*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = [Link]("color");
[Link]("text/html");
PrintWriter pw = [Link]();
[Link]("<B>The selected color is: ");
[Link](color);
[Link]();
}
}
Compile the servlet and perform the same steps as described in the previous section to test it.
Using Cookies
Now, let’s develop a servlet that illustrates how to use cookies. The servlet is invoked when a form on a web
page is submitted. The example contains three files as summarized here:
File Description
The HTML source code for [Link] is shown in the following listing. This page contains a text field
in which a value can be entered. There is also a submit button on the page. When this button is pressed, the
value in the text field is sent to AddCookieServlet via an HTTP POST request.
<html>
<body>
<center>
<form name="Form1"
method="post"
action="[Link]
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for [Link] is shown in the following listing. It gets the value of the
parameter named "data". It then creates a Cookie object that has the name "MyCookie" and contains the value
of the "data" parameter. The cookie is then added to the header of the HTTP response via the addCookie( )
method. A feedback message is then written to the browser.
import [Link].*;
import [Link].*;
import [Link].*;
public class AddCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get parameter from HTTP request.
String data = [Link]("data");
// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);
// Add cookie to HTTP response.
[Link](cookie);
// Write output to browser.
[Link]("text/html");
PrintWriter pw = [Link]();
[Link]("<B>MyCookie has been set to");
[Link](data);
[Link]();
}
}
The source code for [Link] is shown in the following listing. It invokes the getCookies( )
method to read any cookies that are included in the HTTP GET request. The names and values of these cookies
are then written to the HTTP response. Observe that the getName( ) and getValue( ) methods are called to
obtain this information.
import [Link].*;
import [Link].*;
import [Link].*;
public class GetCookiesServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get cookies from header of HTTP request.
Cookie[] cookies = [Link]();
// Display these cookies.
[Link]("text/html");
PrintWriter pw = [Link]();
[Link]("<B>");
for(int i = 0; i < [Link]; i++) {
String name = cookies[i].getName();
String value = cookies[i].getValue();
[Link]("name = " + name +
"; value = " + value);
}
[Link]();
}
}
Compile the servlets. Next, copy them to the appropriate directory, and update the [Link] file, as previously
described. Then, perform these steps to test this example:
1. Start Tomcat, if it is not already running.
2. Display [Link] in a browser.
3. Enter a value for MyCookie.
4. Submit the web page.
After completing these steps, you will observe that a feedback message is displayed by the browser.
Next, request the following URL via the browser:
[Link]
Observe that the name and value of the cookie are displayed in the browser.
In this example, an expiration date is not explicitly assigned to the cookie via the setMaxAge( ) method of
Cookie. Therefore, the cookie expires when the browser session ends. You can experiment by using
setMaxAge( ) and observe that the cookie is then saved on the client machine
Session Tracking
HTTP is a stateless protocol. Each request is independent of the previous one. However, in some applications,
it is necessary to save state information so that information can be collected from several interactions between
a browser and a server. Sessions provide such a mechanism.
A session can be created via the getSession( ) method of HttpServletRequest. An HttpSession object is
returned. This object can store a set of bindings that associate names with objects. The setAttribute( ),
getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage these
bindings. Session state is shared by all servlets that are associated with a client.
The following servlet illustrates how to use session state. The getSession( ) method gets the current session.
A new session is created if one does not already exist. The getAttribute( ) method is called to obtain the object
that is bound to the name "date". That object is a Date object that encapsulates the date and time when this
page was last accessed. (Of course, there is no such binding when the page is first accessed.) A Date object
encapsulating the current date and time is then created. The setAttribute( ) method is called to bind the name
"date"0020to this object.
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get the HttpSession object.
HttpSession hs = [Link](true);
// Get writer.
[Link]("text/html");
PrintWriter pw = [Link]();
[Link]("<B>");
// Display date/time of last access.
Date date = (Date)[Link]("date");
if(date != null) {
[Link]("Last access: " + date + "<br>");
}
// Display current date/time.
date = new Date();
[Link]("date", date);
[Link]("Current date: " + date);
}
}
When you first request this servlet, the browser displays one line with the current date and time information. On
subsequent invocations, two lines are displayed. The first line shows the date and time when the servlet was last
accessed. The second line shows the current date and time.
JSP(JavaServer Pages)
JavaServer Pages (JSP) is a technology for developing web pages that support dynamic content
which helps developers insert java code in HTML pages by making use of special JSP tags.
Using JSP, you can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
Advantages of JSP:
vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to
have plenty of println statements that generate the HTML.
JSP Processing:
The following steps explain how the web server creates the web page using JSP:
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to a
JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of
.html.
The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements
and all JSP elements are converted to Java code that implements the corresponding
dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes
it. During execution, the servlet produces an output in HTML format, which the servlet
engine passes to the web server inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML
content.
Finally web browser handles the dynamically generated HTML page inside the HTTP
response exactly as if it were a static page.
LIFE CYCLE:
A JSP life cycle can be defined as the entire process from its creation till the destruction which
is similar to a servlet life cycle with an additional step which is required to compile a JSP into
servlet.
Compilation
Initialization
Execution
Cleanup
JSP Compilation:
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile
the page. If the page has never been compiled, or if the JSP has been modified since it was last
compiled, the JSP engine compiles the page.
JSP Initialization:
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If
you need to perform JSP-specific initialization, override the jspInit() method:
// Initialization code...
Typically initialization is performed only once and as with the servlet init method, you
generally initialize database connections, open files, and create lookup tables in the jspInit
method.
JSP Execution:
This phase of the JSP life cycle represents all interactions with requests until the JSP is
destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP
engine invokes the _jspService() method in the JSP.
{
// Service handling code...
The _jspService() method of a JSP is invoked once per a request and is responsible for
generating the response for that request and this method is also responsible for generating
responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.
JSP Cleanup:
The destruction phase of the JSP life cycle represents when a JSP is being removed from use
by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override
jspDestroy when you need to perform any cleanup, such as releasing database connections or
closing open files.
{
// Your cleanup code goes here.
JSP Elements :
1. JSP Comments
2. JSP Scriptlets
3. JSP Expression
4. JSP Directives
5. JSP Declaration
1. JSP Comments
Since JSP is built on top of HTML, we can write comments in JSP file like html comments
as
These comments are sent to the client and we can look it with view source option of
browsers.
This comment is suitable for developers to provide code level comments because these are
not sent in the client response.
2. JSP Scriptlets
Scriptlet tags are the easiest way to put java code in a JSP page. A scriptlet tag starts with <%
and ends with %>.
Any code written inside the scriptlet tags go into the _jspService()method. For example:
<%
Date="+d);
%>
3. JSP Expression
Since most of the times we print dynamic data in JSP page
using [Link]() method, there is a shortcut to do this through JSP Expressions. JSP
Expression starts with <%= and ends with %>.
4. JSP Directives
JSP Directives are used to give special instructions to the container while JSP page is getting
translated to servlet source code. JSP directives starts
with <%@and ends with %>
For example, in above JSP Example, I am using page directive to to instruct container JSP
translator to import the Date class.
5. JSP Declaration
JSP Declarations are used to declare member methods and variables of servlet class. JSP
Declarations starts with <%! and ends with %>.
For example we can create an int variable in JSP at class level as <%! public static int
count=0; %>
JSP supports nine automatically defined variables, which are also called implicit objects. These
variables are:
Objects Description
out This is the PrintWriter object used to send output to the client.
JSP Directives:
A JSP directive affects the overall structure of the servlet class. It usually has the following form:
Directive Description
<%@ include ... %> Includes a file during the translation phase.
There is only one syntax for the Action element, as it conforms to the XML standard:
Action elements are basically predefined functions and there are following JSP actions
available:
Syntax Purpose
Example :
<html>
<body>
<%
%>
Result</body>
:
</html>
Hello HIOX
JSP Architecture
JSP architecture gives a high-level view of the working of JSP. JSP architecture is a 3 tier architecture.
It has a Client, Web Server, and Database. The client is the web browser or application on the user side.
Web Server uses a JSP Engine i.e; a container that processes JSP. For example, Apache Tomcat has a built-
in JSP Engine. JSP Engine intercepts the request for JSP and provides the runtime environment for the
understanding and processing of JSP files. It reads, parses, build Java Servlet, Compiles and Executes
Java code, and returns the HTML page to the client. The webserver has access to the Database. The
following diagram shows the architecture of JSP.
Now let us discuss JSP which stands for Java Server Pages. It is a server-side technology. It is used for
creating web applications. It is used to create dynamic web content. In this JSP tags are used to insert JAVA
code into HTML pages. It is an advanced version of Servlet Technology. It is a Web-based technology that
helps us to create dynamic and platform-independent web pages. In this, Java code can be inserted in HTML/
XML pages or both. JSP is first converted into a servlet by JSP container before processing the client’s
request. JSP Processing is illustrated and discussed in sequential steps prior to which a pictorial media is
What is JSP?
In Java, JSP stands for Java Server Pages. It is a server-side technology which is used for creating web
applications. It is used to create dynamic web content. JSP consists of both HTML tags and JSP tags. In this, JSP
tags are used to insert JAVA code into HTML pages. It is an advanced version of Servlet Technology i.e. a
web-based technology that helps us to create dynamic and platform-independent web pages. In this, Java code
can be inserted in HTML/ XML pages or both. JSP is first converted into a servlet by the JSP container before
processing the client’s request. JSP has various features like JSP Expressions, JSP tags, JSP Expression Language,
etc.
How JSP more advantageous than Servlet?
They are easy to maintain.
No recompilation or redeployment is required.
Less coding is required in JSP.
JSP has access to the entire API of JAVA.
JSP are extended version of Servlet.
Features of JSP
Coding in JSP is easy : As it is just adding JAVA code to HTML/XML.
Reduction in the length of Code : In JSP we use action tags, custom tags etc.
Connection to Database is easier : It is easier to connect website to database and allows to read or
write data easily to the database.
JSP provides several predefined objects that developers can use without explicitly declaring them. These
objects help in handling HTTP requests, responses, sessions, and application-wide data.
JSP Variables
<%
int count = 10;
String message = "Hello, JSP!";
%>
b)Declaration Variables (<%! %>)
These are declared at the class level and persist across requests.
Example:
<%!
int counter = 0;
%>
JSP variables can exist in different scopes, which define how long they remain accessible.
jsp
CopyEdit
<%
[Link]("username", "JohnDoe");
%>
b) Request Scope ([Link]/getAttribute)
The variable persists throughout a single request, useful for passing data between JSP pages.
Example:
jsp
CopyEdit
<%
[Link]("userRole", "admin");
%>
c) Session Scope ([Link]/getAttribute)
jsp
CopyEdit
<%
[Link]("loggedInUser", "Alice");
%>
d) Application Scope ([Link]/getAttribute)
The variable is shared across the entire application and is accessible by all users.
Example:
jsp
CopyEdit
<%
[Link]("appName", "MyWebApp");
%>
<%
String userName = "John"; // Scriptlet variable
[Link]("userRole", "Admin"); // Request scope variable
[Link]("userEmail", "john@[Link]"); // Session scope variable
%>
</body>
</html>