0% found this document useful (0 votes)
43 views89 pages

Servlets - Servlet Overview and Architecture (Unit 5)

Uploaded by

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

Servlets - Servlet Overview and Architecture (Unit 5)

Uploaded by

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

WEB TECHNOLOGY

KCS-602

by

Dr. Seema Maitrey


(M.Tech(CE), Ph.D(CSE)

Department of Computer Science &


Engineering
Contents

❑ SERVLET – SERVLET OVERVIEW

❑ SERVLET ARCHITECTURE

❑ APACHE TOMCAT

❑ SERVLET APPLICATION
Servers
• A server is a computer that responds to
requests from a client
– Typical requests: provide a web page, upload or
download a file, send email
• A server is also the software that responds to
these requests; a client could be the browser
or other software making these requests
• Any computer can be a server
– It is not unusual to have server software and
client software running on the same computer
3
Web Server: also known as HTTP Server, it
can handle HTTP Requests send by client and
responds the request with an HTTP Response.

Web Container: Also known as Servlet


Container and Servlet Engine. It is a part of Web
Server that interacts with Servlets. This is the
main component of Web Server that manages
the life cycle of Servlets.

Web Application: Referred as webapp.


Basically the project is your web application, it is
the collection of servlets.
Apache
• Apache is a very popular server
– 66% of web sites on the Internet use Apache
• Apache is:
– Full-featured and extensible
– Efficient
– Robust
– Secure (at least, more secure than other servers)
– Up to date with current standards
– Open source
– Free
5
Ports
• The http: at the beginning signifies a
particular protocol (communication
language), the Hypertext Transfer Protocol
• The :80 specifies a port
• By default, Web server listens to port 80
– The Web server could listen to any port it
chose
– This could lead to problems if the port was in
use by some other server
– For testing servlets, we typically have the
server listen to port 8080
6
Tomcat
• Tomcat is the Servlet Engine, handles servlet
requests for Apache
– Tomcat is a “helper application” for Apache
– It’s best to think of Tomcat as a “servlet container”
• Apache can handle many types of web services
– Apache can be installed without Tomcat
– Tomcat can be installed without Apache
– By itself, Tomcat can handle web pages, servlets, and
JSP
• Apache and Tomcat are open source (and
7therefore free)
Server-side programming
• In many cases, client-side applications will be
insufficient
– Heavy processing
– Communication with other clients
– Data available on server-side only
• It may be useful to send the request to the server,
and to process it there.
• A number of technologies available: CGI, Servlets,
JSP, ASP, PHP and others
• We will look at CGI, Servlets and JSP.
CGI Scripts
• CGI stands for “Common Gateway Interface”
• CGI is a standard programming interface to Web servers that allows building
dynamic and interactive Web sites

• CGI is not a programming language.


Client sends a request to server

Server starts a CGI script


client
Script computes a result for server
server
and quits client
script
Server returns response to client
Another client sends a request
Server starts the CGI script again
Etc.

9
Servlets
• A servlet is like an applet, but on the server side

Client sends a request to server

Server starts a servlet


client server
Servlet computes a result for
server and does not quit client
servlet
Server returns response to client
Another client sends a request
Server calls the servlet again
Etc.

10
Servlets vs. CGI scripts
• Advantages:
– Running a servlet doesn’t require creating a separate
process each time
– A servlet stays in memory, so it doesn’t have to be reloaded
each time
– There is only one instance handling multiple requests, not a
separate instance for every request
• Disadvantage:
– Less choice of languages (CGI scripts can be in any language)

11
Cont…
• Servlets are generic extensions to Java-enabled
servers
• Servlets are secure, portable, and easy to use
replacement for CGI
• Servlet is a dynamically loaded module that
services requests from a Web server
• Servlets are executed within the JVM
• Because the servlet is running on the server
side, it does not depend on browser
compatibility
Advantages of Servlets
 Efficiency
More efficient – uses lightweight java threads
 Persistency
Servlets remain in memory , can maintain state b/w requests
 Portability
Servlets are written in Java, so are platform independent
 Robustness
Error handling, Garbage collector to prevent problems with
memory leaks
Large class library – network, file, database, distributed
object components, security, etc.
Cont.
.
Security
– Security provided by the server as well as the
Java Security Manager
Powerful
– Servlets can directly talk to web server
– Facilitates db connection pooling, session
tracking etc.
Class and interface of Servlets
- A servlet is any class that implements the
javax.servlet.Servlet interface
– In practice, most servlets extend the
javax.servlet.http.HttpServlet class
– Some servlets extend
javax.servlet.GenericServlet instead

• Servlets, like applets, usually lack a main


method, but must implement or override
certain other methods
15
A Servlet’s Job
• Read explicit data sent by client (form data)
• Read implicit data sent by client
(request headers)
• Generate the results
• Send the explicit data back to client (HTML)
• Send the implicit data to client
(status codes and response headers)
Execution of Java Servlet
Request
Web Web
Servlet
Browser Server
Response
Servlet API
• use Servlet API to create servlets.

• Defined in javax.servlet package

• Provides core servlet functionality- just extend it,


accepts query, returns response
Every Servlet must implement the java.servlet.Servlet interface,

you can do it by extending one of the following two classes:


javax.servlet.GenericServlet or javax.servlet.http.HttpServlet.
- First one is for protocol independent Servlet ,second one for
http Servlet.
Cont…

Let’s see the hierarchy of packages:


javax.servlet.Servlet

• Base interface of Java Servlet API


• Defines all the lifecycle methods of servlet.
Since this is an interface, any class
implementing Servlet interface has to
implement all its methods.
• Provides 3 life cycle methods that are used to
initialize the servlet, to service the requests, and to
destroy the servlet
These are invoked by the web container.

• Also provide 2 non-life cycle methods.


Cont..

Method Description

public void init(ServletConfig config) initializes the servlet. It is the life cycle
method of servlet and invoked by the
web container only once.

public void service(ServletRequest provides response for the incoming


request,ServletResponse response) request. It is invoked at each request by
the web container.

public void destroy() is invoked only once and indicates that


servlet is being destroyed.

public ServletConfig getServletConfig() returns the object of ServletConfig.


public String getServletInfo() returns information about servlet such
as writer, copyright, version etc.
GenericServlet class
• Implements Servlet, ServletConfig and Serializable interfaces.
• Provides the implementation of all the methods of these
interfaces except the service method.

• It can handle any type of request so it is protocol-independent.

• For creating a Generic Servlet we must extend :


javax.servlet.GenericServlet class.

• This class has an one abstract service() method. Subclass of


GenericServlet should always override the service() method.
.
Cont..

Signature of service() method:


public abstract void service(ServletRequest request,
ServletResponse response) throws ServletException,
java.io.IOException
• The service() method accepts two arguments ServletRequest
object and ServletResponse object.
request object tells the servlet about the request made by client
response object is used to return a response back to the client.

How Generic
Servlet works?
HTTPSERVLET
•For creating Http Servlet we 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 , next➔
Cont…
• doGet() – called by servlet service method to handle the HTTP
GET request from client where 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.
Cont…
Interfaces in javax.servlet.http package Interfaces in javax.servlet package
•HttpSession •Servlet
•HttpServletRequest •ServletRequest
•HttpServletResponse •ServletResponse
•HttpSessionAttributeListener •ServletConfig
•ServletContext
more… •RequestDispatcher
•ServletRequestListener
more…

Classes in javax.servlet package


Classes in javax.servlet.http package
•GenericServlet
•HttpServlet
•ServletInputStream
•Cookie
•ServletOutputStream
•HttpSessionEvent
•ServletException
•HttpSessionBindingEvent
•ServletRequestWrapper
•HttpServletRequestWrapper
•ServletRequestEvent
•HttpServletResponseWrapper
•ServletResponseWrapper
more…
more…
welcome-file-list tag in web.xml file of Project

➢The tag <welcome-file-list> is used for specifying the files that


needs to be invoked by server by default, if you do not specify
a file name while loading the project on browser.
➢For e.g. You have created a project named “MyServletProject”
and you have few html pages and servlet classes defined in
the project. However in browser you have given the url like
this: http://localhost:8080/MyServletProject
➢Usually we give the complete path like
this:http://localhost:8080/MyServletProject/index.html. However
if you have given the path like above then the webserver will
look for the <welcome-file-list> tag in your project’s web.xml
file.
<web-app>
....
<welcome-file-list>
<welcome-file>myhome.htm</welcome-file>
<welcome-file>myindex.htm</welcome-file>
<welcome-file>mydefaultpage.htm</welcome-file>
</welcome-file-list>
....
</web-app>
Based on the welcome file list, server would look for the myhome.htm
page if this doesn’t exist then the second welcome file myindex.html and
so on till it finds a valid welcome file.
Note: If the <welcome-file-list> tag is not defined in web.xml or the
welcome files defined in the <welcome-file> tags does not exist then the
server would look for the following files in the given sequence:
1) index.html 2) index.htm 3) index.jsp
Java Servlet Architecture
• Two packages make up the servlet architecture
– javax.servlet
• Contains generic interfaces and classes that are implemented and
extended by all servlets
– javax.servlet.http
• Contains classes that are extended when creating HTTP-specific servlets
• The heart of servlet architecture is the interface class
javax.servlet.Servlet

• It provides the framework for all servlets

• Defines five basic methods – init, service, destroy,


getServletConfig and getServletInfo
Servlet Architecture: 3-Tier system
• Tier 1: Client
– HTML browser
– Java client
• Tier 2: Servlets
– embody business logic
– secure, robust
• Tier 3: Data Sources
– Java can talk to SQL, JDBC, OODB, files,
etc…
Web Application model

Enterprise Information
Client Tier Middle Tier System (EIS) Tier

SQL
application Web Container

Servlet Database
Servlet
browser JSP

File
system
Servlet Name
• Servlet is invoked using its name
–Servlet should be located in appropriate
directory

• A servlet’s name is its class name

• Name is usually a single word


–Possibly with a package name and dots
The HelloWorld Servlet
import javax.servlet.*;
import java.io.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest req,
ServletResponse res) throws IOException,
ServletException{
res.setContentType("text/plain");
ServletOutputStream out = res.getOutputStream();
out.println("Hello, World!");
}
}
Life Cycle of a Servlet
• Servlets operate in the context of a request and
response model managed by a servlet engine
The engine does the following
– Loads the servlet when it is first requested
– Web Container creates the instance of it and
that is created only once in the life cycle.
– Calls the servlet’s init( ) method
– Handles any number of requests by calling the
servlet’s service( ) method
– When shutting down, calls each servlet’s
destroy( ) method
Cont..
Steps Description
Loading Servlet Class A Servlet class is loaded when first request for the servlet is
received by the Web Container.

Servlet instance creation After the Servlet class is loaded, Web Container creates the
instance of it and that is created only once in the life cycle.

Call to the init() method : init() method is called by the Web Container on servlet
Signature of init() method : public void instance to initialize the servlet.
init(ServletConfig config) throws
ServletException

Call to the service() method This method is called by the containers each time the request
Signature of service() method: for servlet is received. The service() method will then call the
public void service(ServletRequest doGet() or doPost() methods based on the type of the HTTP
request, ServletResponse response) request
throws ServletException, IOException

Call to destroy() method: The Web Container call the destroy() method before removing
servlet instance, giving it a chance for cleanup activity
Cont… Life Cycle
Free Servlet and JSP Engines
• Apache Tomcat
– http://jakarta.apache.org/tomcat/
• Allaire/Macromedia JRun
– http://www.macromedia.com/software/jrun/
• New Atlanta ServletExec
– http://www.servletexec.com/
• Gefion Software LiteWebServer
– http://www.gefionsoftware.com/LiteWebServer/
• Caucho's Resin
– http://www.caucho.com/
Compiling and Invoking Servlets
• Set your CLASSPATH
– C:\xampp\tomcat\lib\servlet-api.jar

– Put your servlet classes in proper location


– Locations vary from server to server. E.g.,
• tomcat_install_dir\webapps\examples\WEB-INF\classes

– Invoke your servlets

– http://host/servlet/ServletName

– Custom URL-to-servlet mapping (via web.xml)


A Simple Servlet That Generates Plain Text
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet


{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
out.println("Hello World");
} }
A Servlet That Generates HTML
public class HelloWWW extends HttpServlet {
public void doGet(HttpServletRequest
request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(docType +
"<HTML>\n" +
"<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" +
"<BODY>\n" +
"<H1>Hello WWW</H1>\n" +
"</BODY></HTML>");
} }
HelloWWW Result
Scalability of servlets
 The servlet is only recompiled if it was changed otherwise
the already compiled class is loaded
- Faster response times as servlet does not need to be recompiled

 The servlet can be kept in memory for a long time to


service many sequential requests
- Faster response times as servlet does not need to be reloaded

 Only one copy of the servlet is held in memory even if


there are multiple concurrent requests
- Less memory usage for concurrent requests and no need to load
another copy of the servlet and create a new process to run it.
❑APACHE TOMCAT

❑SERVLET APPLICATION
APACHE TOMCAT
• Apache is most common HTTP Web Server on Internet.
• The Tomcat server is a Java-based Web Application
container used to run Servlet and JSP Web applications.
• Tomcat was chosen to be the official Sun Web
Component (JSP/Servlet) Container Reference
Implementation.
• It is an open source Java Servlet application server used
to deploy Java applications after they are built with JSP
and Servlets.
• It can be used as a stand-alone product or it can be
integrated with the Apache server.
45
What is a Container?
• Containers are interface b/w a component
and low-level platform-specific functionality
that supports the component.

Web container :
Manages the execution of JSP page and servlet
components for J2EE applications. Web
components and their container run on the J2EE
server.
46
J2EE Server and Containers
Client Web Server (Apache)

Tomcat
Browser
Servlet JSP page

Java Web Container

Application
Client
Database
Client
Container Session Entity
Bean Bean

Client Machine
EJB Container
JBoss,
WebSphere,
WebLogic, etc

47
Installation of Apache Tomcat
• Java is already installed on PCs
The installation guides for TOMCAT:
- Initiate download of Tomcat from the site
http://tomcat.apache.org/

• After downloading follow the instructions to


start installation.

48
Start Up Tomcat
• Tomcat can be started by following command:
C:\xampp\tomcat\bin\startup.bat (Windows)

• After startup, the default web applications


included with Tomcat will be available by visiting:
http://localhost:8080/

Shut Tomcat can be shut down by executing:


Down
Tomcat
• C:\xampp\tomcat\bin\shutdown (Windows)
49
Advantages of Tomcat
1) It is an open source application server
2) It is a light weight server (no EJB)
3) It is easily configured with Apache and IIS
4) Very stable on Unix systems
5) Good documentation online
6) Java Sun compliant
7) Does not require a lot of memory at startup
8) It is free, yet high quality!
50
Steps to Create Servlet Application using Tomcat

After installing Tomcat Server, follow the steps :

1. Create directory structure for your application.


2. Create a Servlet
3. Compile the Servlet
4. Create Deployement Descriptor for your application
5. Start the server and deploy the application

All these 5 steps are explained in details below, lets


create our first Servlet Application.
1. Creating the Directory Structure
A unique directory structure defined by Sun Microsystem, must be
followed to create a servlet application.
Cont…
Create directory structure
Create directory structure inside Apache-Tomcat\webapps directory.

• All HTML, static files(images, css etc) are kept directly under Web
application folder(here First).
• Make folder WEB-INF inside your web app(First).
• Inside WEB-INF, make 2 folders: Lib and classes
• All the Servlet classes are kept inside classes folder.
• Lib contains two (.jar) files. Copy from their resp. location
i) for servlet, provide→ servlet-api.jar // Copy from:
C:\xampp\tomcat\lib\servlet-api.jar

ii) for mysql→ mysql-connector.jar //Copy from C:\Program


Files\Java\jre1.8.0_271\lib\ext\mysql-connector.jar

• The web.xml (deployement descriptor) file is kept under WEB-INF folder.


2. Creating a Servlet

There are 3 different ways to create a servlet.


• By implementing Servlet interface
• By extending GenericServlet class
• By extending HttpServlet class
But mostly a servlet is created by extending
HttpServlet abstract class because it provides
methods to handle http requests such as
doGet(), doPost etc..
Cont.. Write below code in a notepad file and save it as MyServlet.java
anywhere on your PC. Compile it from there and paste the class file
into WEB-INF/classes/ directory that you have to create inside
Tomcat/webapps directory.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResposne
response)
throws ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello Readers</h1>");
out.println("</body></html>"); }}
3. Compiling a Servlet
• To compile a Servlet a JAR file is required. In
Apache Tomcat server servlet-api.jar file is
required to compile a servlet class.
• Download servlet-api.jar file.
• Paste servlet-api.jar file inside
Java\jdk\jre\lib\ext directory.
• Compile the Servlet class.
• After compiling Servlet class, paste the class
file into WEB-INF/classes/ directory.
4. Create Deployment Descriptor

• Deployment Descriptor(DD) is an XML


document that is used by Web Container to
run Servlets and JSP pages. DD is used for
several important purposes such as:
– Mapping URL to Servlet class.
– Initializing parameters.
– Defining Error page.
– Security roles.
– Declaring tag libraries.
Cont…

To create a
simple
web.xml
file for our
web
application
.
5. Start the Server

• Double click on the startup.bat file

Or,
execute below command on prompt:
–C:\apache-tomcat-7.0.14\bin\startup.bat
6. Starting Tomcat Server for the first time
Its needed to set JAVA_HOME in the Enviroment variable

•.
7. Run Servlet Application
• Open Browser and type--→

http:localhost:8080/First/hello
Cont… To Run HTML(index.html) in Tomcat

To start with an index file, make it in any editor, save with extension
.html and keep it parallel to WEB-INF.

There is no need to mention its name while execution, as it gets


executed automatically by the tomcat
Redirecting Requests

to

other Resources
FORWARD()
RequestDispatcher
interface INCLUDE()

HttpServletResponse sendRedirect
interface method()
Redirecting Requests to Other Resources
(1)RequestDispatcher interface(a part of Servlet API)
It defines an object that receives the request from client and
dispatches it to the resource(such as servlet, JSP, HTML file). This
interface has following two methods: forward() and include()
a) Public void It forwards the request from
forward(ServletRequest req, one servlet to another
ServletResponse res): resource (such as servlet,
JSP, HTML file).

b) public void It includes the content of the


include(ServletRequest req, resource(such as servlet, JSP,
ServletResponse res): HTML file) in the response.
Cont….
forward() vs include() method
include() : 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.
forward (): Taking the same example with forward, 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 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.
(2) SendRedirect() of HttpServletResponse interface

• Used to redirect response to another resource, it may be


servlet, jsp or html file.
• It works at client side because it uses the url bar of browser to
make another request. So, it can work inside & outside server.
• This approach generally is used when the control needs to be
forwarded outside the web application. For example we need
to forward the control to google.com . It does not mean that we
cannot use redirect within same web application , but this
approach is ideally used to redirect control to different domain.
Cont…

Difference b/w forward() & sendRedirect() method

forward() method sendRedirect() method


Works at server side; ie. intended to forward a works at client side; ie. used to send
request to resources within the web control outside the web application.
application. Servlet can forward the request to
another servlet or JSP which are part of same
web application.
It sends the same request and response It always sends a new request.
objects to another servlet.
It can work within the server only. can be used within & outside server.
Control is forwarded by container and Browser takes the responsibility.
browser is not involved But gets changed while redirect.
To validate this , in case of forward, browser
URL is not changed
Example: Example:
request.getRequestDispacher("servlet2").forw response.sendRedirect("servlet2");
ard(request,response);
Program of sendRedirect method in servlet

Creating custom google search using sendRedirect

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletRespo
nse res)
throws ServletException,IOException {
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
res.sendRedirect("http://www.google.com");
pw.close(); }}
ServletConfig Interface
An object of ServletConfig is created by the web container for each servlet.
This object can be used to get configuration information from web.xml file.

Advantage of ServletConfig
Don't need to edit the servlet file if information is modified from the web.xml file.

Methods of ServletConfig interface

1.public String getInitParameter(String name):Returns the parameter


value for the specified parameter name.
2.public Enumeration getInitParameterNames():Returns an
enumeration of all the initialization parameter names.
3.public String getServletName():Returns the name of the servlet.
4.public ServletContext getServletContext():Returns an object of
ServletContext.
Program: getting the one initialization parameter from the web.xml file and printing this
information in the servlet.
DemoServlet.java web.xml
import java.io.*; <web-app>
import javax.servlet.*; <servlet>
import javax.servlet.http.*; <servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
public class DemoServlet extends HttpServlet {
<init-param>
public void doGet(HttpServletRequest request, <param-name>driver</param-name>
HttpServletResponse response) <param-
throws ServletException, IOException { value>sun.jdbc.odbc.JdbcOdbcDriver</param-
value>
response.setContentType("text/html"); </init-param> </servlet>
PrintWriter out = response.getWriter();
ServletConfig config=getServletConfig(); <servlet-mapping>
String driver=config.getInitParameter("driver <servlet-name>DemoServlet</servlet-name>
"); <url-pattern>/servlet1</url-pattern>
out.print("Driver is: "+driver); </servlet-mapping> </web-app>
out.close();
} }
SERVLETCONTEXT INTERFACE
✓ An object of ServletContext is created by the web container at time of deploying the
project. This object can be used to get context information from web.xml file. There is
only one ServletContext object per web application.
✓ If any information is shared to many servlet, it is better to provide it from the web.xml file
using the <context-param> element.
Advantage of ServletContext
Easy to maintain if any information is shared to all the servlet, it is better to
make it available for all the servlet. We provide this information from the
web.xml file, so if the information is changed, we don't need to modify the
servlet. Thus it removes maintenance problem.
Usage of ServletContext Interface
• The object of ServletContext provides an interface between the container
and servlet.
• Can be used to get configuration information from the web.xml file.
• Can be used to set, get or remove attribute from the web.xml file.
• Used to provide inter-application communication.
ServletContext interface

Commonly used methods of ServletContext interface


1. public String getInitParameter(String name):Returns parameter value for the specified parameter name.
2. public Enumeration getInitParameterNames():Returns the names of the context's initialization
parameters.
3. public void setAttribute(String name,Object object):sets the given object in the application scope.
4. public Object getAttribute(String name):Returns the attribute for the specified name.
5. public Enumeration getInitParameterNames():Returns the names of the context's initialization
parameters as an Enumeration of String objects.
6. public void removeAttribute(String name):Removes the attribute with the given name from the servlet
context.
Example of ServletContext to get the initialization parameter
DemoServlet.java web.xml

import java.io.*; <web-app>


import javax.servlet.*;
import javax.servlet.http.*; <servlet>
public class DemoServlet extends HttpServlet{ <servlet-name>DemoServlet</servlet-
public void doGet(HttpServletRequest req,HttpServletRespons name>
e res) <servlet-class>DemoServlet</servlet-
throws ServletException,IOException class>
{ </servlet>
res.setContentType("text/html");
PrintWriter pw=res.getWriter(); <context-param>
<param-name>dname</param-name>
//creating ServletContext object <param-
ServletContext context=getServletContext(); value>sun.jdbc.odbc.JdbcOdbcDriver</par
am-value>
//Getting the value of the initialization parameter and printing </context-param>
it
String driverName=context.getInitParameter("dname"); <servlet-mapping>
pw.println("driver name is="+driverName); <servlet-name>DemoServlet</servlet-
name>
pw.close(); <url-pattern>/context</url-pattern>
</servlet-mapping>
}}
</web-app>
Example of ServletContext to get all the initialization parameters
DemoServlet.java web.xml
import java.io.*; <web-app>
import javax.servlet.*; <servlet>
import javax.servlet.http.*;
<servlet-name>DemoServlet</servlet-name>
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res) <servlet-class>DemoServlet</servlet-class>
throws ServletException,IOException </servlet>
{ <context-param>
res.setContentType("text/html"); <param-name>dname</param-name>
PrintWriter out=res.getWriter(); <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-
value>
ServletContext context=getServletContext();
Enumeration<String> e=context.getInitParameterNames(); </context-param>
<context-param>
String str=""; <param-name>username</param-name>
while(e.hasMoreElements()){ <param-value>system</param-value>
str=e.nextElement(); </context-param>
out.print("<br> "+context.getInitParameter(str));
<context-param>
}
}} <param-name>password</param-name>
<param-value>oracle</param-value>
</context-param>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>

The servletconfig object refers to the single servlet whereas servletcontext object refers to the whole
web application.
❑ SESSION HANDLING

❑ COOKIES

❑ URL RE-WRITING

❑ HIDDEN FIELDS
Managing Session in Servlets
We all know that HTTP is a stateless protocol. All requests and responses are independent.
But sometimes you need to keep track of client's activity across multiple requests. For eg.
When a User logs into your website, not matter on which web page he visits after logging in,
his credentials will be with the server, until he logs out. So this is managed by creating a
session.

Session Management is a mechanism used by the Web container to store session


information for a particular user. There are four different techniques used by Servlet
application for session management. They are as follows:

1. Cookies
2. Hidden form field
3. URL Rewriting
4. HttpSession

Session is used to store everything that we can get from the client from all the requests the
client makes.
How Session Works

Basic concept: whenever a user starts using our application, we can save a
unique identification information about him, in an object which is available
throughout the application, until its destroyed. So wherever the user goes,
we will always have his information and we can always manage which user is
doing what. Whenever a user wants to exit from your application, destroy
the object with his information.
1) HttpSession
• HttpSession object is used to store entire session with a specific client. We can store, retrieve
and remove attribute from HttpSession object.
• Any servlet can have access to HttpSession object throughout the getSession() method of the
HttpServletRequest object.
How HttpSession works:

1. On client's first request, the Web Container generates a unique session ID and gives it back to the
client with response. This is a temporary session created by web container.
2. The client sends back the session ID with each request. Making it easier for the web container to
identify where the request is coming from.
3. The Web Container uses this ID, finds the matching session with the ID and associates the session
with the request.
Some Important Methods of Servlet HttpSession
Methods Description
long getCreationTime() returns the time when the session was created, measured in
milliseconds since midnight January 1, 1970 GMT.

String getId() returns a string containing the unique identifier assigned to the
session.

long getLastAccessedTime() returns last time the client sent a request associated with the
session

int getMaxInactiveInterval() returns the maximum time interval, in seconds.

void invalidate() destroy the session


boolean isNew() returns true if the session is new else false

void setMaxInactiveInterval(int Specifies the time, in seconds,after servlet container will


interval) invalidate the session.
2) Using Cookies for Session Management in Servlet

• Cookies are small pieces of information that are sent in response from web server to client.
• Cookies are the simplest technique used for storing client state.
• Cookies are stored on client's computer.
• They have a lifespan and are destroyed by the client browser at the end of that lifespan.
• Using Cookies for storing client state has one shortcoming though, if the client has turned of
Cookie saving settings in his browser then, client state can never be saved because the
browser will not allow the application to store cookies.

Servlet: Cookies API

➢Cookies are created using Cookie class present in Servlet API.


➢Cookies are added to response object using the addCookie() method.
➢getCookies() method is used to access the cookies that are added to
response object.
Example: creating and using Cookies
Example demonstrating usage of Cookies
Types of Cookies
There are two types of cookies. They are as following:
i) Session cookies ii) Persistent cookies

1) Session cookies:
The session cookies do not have any expiration time. It is present in the browser memory.
When the web browser is closed then the cookies are destroyed automatically.

2) Persistent Cookies:
The Persistent cookies have an expiration time. It is stored in the hard drive of the user and it
is destroyed based on the expiry time.

How cookies works?


When a user Start a web and request information from the website. The
website server replies and it sends a cookie. This cookie is put on the hard
drive. Next time when you return to the same website your computer will send
the cookies back. Now the website server identifies the data and sale your
information to other sellers.
3) Using URL Rewriting for Session Management in Servlet
• If the client has disabled cookies in the browser then session management using cookie
wont work. In that case URL Rewriting can be used as a backup. URL rewriting will always
work.

• In URL rewriting, a token(parameter) is added at the end of the URL. The token consist of
name/value pair seperated by an equal(=) sign. For Example:

➢ When the User clicks on the URL having parameters, the request goes to the Web Container with
extra bit of information at the end of URL. The Web Container will fetch the extra part of the
requested URL and use it for session management.

➢ The getParameter() method is used to get the parameter value at the server side.
4) Using Hidden Form Field for Session Management in Servlet
• Hidden form field can also be used to store session information
for a particular client.
• In this case user information is stored in hidden field value and
retrieved from another servlet.
Advantages:
• Does not have to depend on browser whether the cookie is disabled or not.
• Inserting a simple HTML Input field of type hidden is required. Hence, its
easier to implement.

Disadvantage:

Extra form submission is required on every page. This is a big overhead.


Example demonstrating usage of Hidden Form Field for Session
Thank
You

You might also like