You are on page 1of 137

UNIT-IV

J2EE Platform:
• Enterprise Architecture Styles
• Containers and Technologies
Servlet Programming:
• Overview of Java Servlet API Text book
• Servlet Implementation Professional Java Servler
• Servlet Configuration Programming
• Servlet Exceptions by Subrahmanyam Allamraju
• Servlet Life cycle,
• Request and Responses.
• Introduction to Web containers: Web Application Structure, Mapping requests to
Applications and Servlets, Securing web Applications and Deployment configuration
• Servlet Sessions, Context and Collaboration: Approaches to Session tracking,
Session Tracking with java servlet API, Servlet Context, Servlet Collaboration.

E.Swathi, CSE, CBIT


J2EE
• Over the years, Java has evolved into 3 different platform, each addressing
a distinct set of programming needs:
• The Java2 Platform, Standard Edition(J2SE): This is the most
commonly used Java platform, consisting of a run-time environment
and a set of APIs for building a wide variety of applications ranging
from applets, through standalone applications that run on various
platforms, to client applications for various enterprise applications.
• The Java 2 Platform, Enterprise Edition(J2EE): This is for a
platform for building server-side applications. Server-side applications
have additional requirements during development phase. J2EE
provides the infrastructure for meeting these needs.
• The Java 2 Platform, Micro Edition(J2ME): This edition enables
the building the Java applications for micro devices.
Enterprise Architecture Styles
• An enterprise means a business organization, and enterprise applications
are those software applications that facilitate various activities in an
enterprise.

• Enterprise applications can be cater to end-users via the Internet, partners


via the Internet or private networks, various business units within the
enterprise via various kinds of user interface.
• Enterprise architecture styles:
1. Two-tier architecture
2. Three-tier architecture
3. N-Tier architecture
4. Enterprise architecture
Two-Tier Architecture
• In 2-tier application, the processing load is given to the client PC while the
server simply acts as a traffic controller between the application and the
data.
• Problems with this approach:
• Limited resources on PC
• Network traffic increases
• Maintenance
Three-Tier Architecture
• In 3-tier application, an application is broken up into three separate logical
layers, each with well-defined set of interfaces.
• The first tier is referred to as the presentation layer and typically consists of a
graphical user interface.
• The middle tier is business layer, consists of the application or business logic.
• The third tier is Data layer, contains the data that is needed for the application.
• The middle tier is the code that the user calls upon to retrieve the desired data.
n-Tier Architecture
• In an n-tier application, the application logic is logically divided by function,
rather than physically.
• N-tier architecture breaks down like this:
• A user interface that handles the user’s interaction with the application-
this can be a web browser running through a firewall, a heavier desktop
application.
• Presentation logic that defines what the user interface displays and how a
user’s requests are handled.
• Business logic that models the application’s business rules, often though
interaction with the application’s data.
• Infrastructure services that provide additional functionality required by the
application components, such as messaging, transactional support.
• The data layer contains the data of enterprise.
n-Tier Architecture

Applications based on this architecture are employing the mode-view-controller


Enterprise Architecture
• To turn an n-tier system into an enterprise system, the middle tier is
extended by allowing for multiple application objects rather than just a
single application.
• These applications must have an interface that allow them to work together
with each other.
• An interface can be a contract. Each object states through its interface that
will accept certain parameters, perform certain operations, and return a
specific set of results.
• With enterprise architecture, we can have multiple applications using a
common set of components across an organization. This promotes the
standardization of business practices by creating a single set of business
functions for the entire organization access.
Enterprise Architecture
Web Server

• A web server is a program running on the server that listens


for incoming requests and services those requests as they
come in.
• Once the web server receives a request, depending on the type
of request the web server might look for a web page, or it
might execute a program on the server.
• It will always return some kind of results to the web browser,
even if its simply an error message saying that it couldn’t
process the request.
• By default the role of a web server is to serve static pages
using the http protocol
• Web servers can be made dynamic by adding additional
processing capability to the server
Tomcat

• Tomcat is a stand alone web server and a servlet container


– It is open source and free for usage
• It is written in Java
– You do not have to be a Java programmer to use it
– It’s web server is not as fully featured as others like Apache
• Installing Tomcat
– Make sure that jdk1.4 (or higher) is installed on your machine
– Download the latest windows version of Tomcat
– Run the installer by double clicking on the download
– The installer checks if JRE and JDK are available for Tomcat
– Accept the license agreement
– Installation directory: c:\Program Files\Apache Tomcat 4.0
– On installation you get a message Completed
Container architecture
• The application server which control and provide services through an
interface is known as a container.
• J2EE container is a runtime to manage application components developed
according to the API specifications, and to provide access to the J2EE
APIs.
• J2EE container helps in deployment and execution of J2EE component.
Container architecture
• Application components: include servlets, JSP pages, EJBs etc. In J2EE,
application components can be packaged into archive files.
• Deployment descriptors: Deployment descriptor is an XML file that describes
the application components. It also includes additional information required by
containers for effectively managing application components.
• The architecture of a container can be divided into four parts:
• Component contract: A set of APIs specified by the container, that your
application components are required to extend or implement.
• Container service APIs: Additional services provided by the container,
which are commonly required for the applications in the container.
• Declarative services: services that the container interposes on your
applications, based on deployment description provided for each
application component, such as security, transactions etc.
• Other container services: other runtime services, related to component life
cycle, resource pooling, garbage collection, etc.
J2EE Architecture - Containers
• J2EE includes one or more containers.
J2EE Architecture
Client Tier

• Client Container has a contract with applications


Applet Container to provide certain functionality to the components
in the application

Applet
Application Container

ClientApp
(JAR file)
Application Container

Deployment
Descriptor
Main AppClass
Public static void main (String args[ ] )
Application

JD JA J J Java Packages,
B X A M Classes, Libraries
C P A S
S

15 of 99
J2EE Architecture
Middle Tier Container

 Web Container
 Manages execution of servlets and JSPs
 Part of web or application server
 Supports HTTP
 EJB Container
 Business Components that contain business logic or rules
 Two types of EJBs
 Session Beans – Logic Oriented and deal with handling client
requests and data processing
 Entity Beand – Strongly coupled with data and deal with data
access and persistence

16 of 99
J2EE Architecture
E-Commerce Scenario

WEB Container J2EE Server

Shopping Cart
Application WEB Container
Catalog Servlet
OrderManager
Application Container Cart Servlet Application Supplier Server
Order WEB Container StockOrder
WEB Container Order Manager (XML)
ClientApp Process Servlet
Servlet

Static
Pages EJB Container

Order Manager
EJBApplication
WEB Container
Order EJB
Database

 Two distinct parts of the applications


 Shopping Cart: Handles consumer side of the store
 Order Manager: Handles back end processing
17 of 99
J2EE Architecture
E-Commerce

 Cart Application
 Catalog servlet gets product data from the database
 Cart servlet keeps track of the customer purchase
 Process servlet processes the order
 Order Process Application
 Processes customer order
 Checks inventory levels (orders new parts from Suppliers)
 Processes payments
 Sends acknowledgement to the client

18 of 99
J2EE Architecture
E-Auctions

Applet Container
Client Tier Browser
PaymentApplet

WEB Container WEB Container WEB Container WEB Container WEB Container
Cluster
Middle Tier Sales/Auction Sales/Auction Sales/Auction
Sales & Auction Payment Payment Payment Cluster
WEB Container WEB Container WEB Container WEB Container WEB Container
Application Application Application Application Application

Database Tier Sales & Auction Payment Database


Database

19 of 99
J2EE Architecture
E-Auctions – Container Ideas

Web Container
Auction Application
Payment Application Registration
Java Package
Post

Payment Search
Descriptor
Static
Deployment Descriptor
Deployment Bid Pages
Static
Pages Purchase
Java Package Offer
History

Payment

Application Container  Two separate applications


 Auction: Deals with bidding and searching
ClientApp
 Payment – Deals with backend financial
processing

20 of 99
J2EE Architecture
E-Auctions

 Client Side uses a web browser to view store


 Auction Application
 Registration Servlet: Registers new users
 Post servlet: Accepts new items for auction
 Search servlet: Allows buyers to search database
 Bid servlet: Allows users to bid on pending items
 Informs the seller of the bid (e-mail)
 Purchase servlet: Processes sales
 History Servlet: Allows bidder/seller to review history of any
item on auction
 Payment Application
 Payment Servlet: Credits the buyer and Debits the seller
(Credit card transactions)

21 of 99
J2ee architecture-containers
• j2EE container is a runtime to manage application
components developed according to the API specifications,
and to provide access to the J2EE APIs.
• Diagram shows the architecture of J2EE in terms of
containers and APIs.
• Architecture shows four containers
1) Web container: for hosting java servlets and JSPs
2) EJB container: for hosting Enterprise javabean
components.
3) Applet container: for hosting java applets.
4) Application client container: for hosting standard java
applications.

E.Swathi, CSE, CBIT


Servlets
• 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.
• Servlets are the Java programs that runs on the Java-enabled web server or
application server. They are used to handle the request obtained from the
web server, process the request, produce the response, then send response
back to the web server.
• Properties of Servlets :
• Servlets work on the server-side.
• Servlets are capable of handling complex requests obtained from web
server.
Servlet architecture
• Execution of Servlets involves six basic steps:
1. The clients send the request to the web server.
2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
4. The servlet processes the request and generates the response in the form
of output.
5. The servlet sends the response back to the web server.
6. The web server sends the response back to the client and the client
browser displays it on the screen.
Job of servlets
1. Reads data send by the user
data could send in form of web page or through java applet or HTTP request
2. Look up any other information about the request that is embedded in the HTTP
request.
This information includes details about browser capabilities,
cookies, the host name of the requesting client, and so on.
3. Generate the results.
contact the database by invoking RMI or CORBA or compute the results directly
4. Format the results inside a document.
5. Set the appropriate HTTP response parameters.
tells to browser that what type of document is being return (eg HTML) and sets
cookies and other caching parameters
6. Send the document back to the client.
document may be a HTML page/ JIF images or compressed files like ZIP files

E.Swathi, CSE, CBIT


Installation and configuration of tomcat in
ubuntu
Softwares required : Apache tomcat and java
Step-1 installing tomcat
Go to google type Apache Tomcat open tomcat.apache.org/
- select tomcat 9 which is latest version and compatible with jdk 1.8/1.7.
- Download tar.gz for ubuntu (windows 32/64bit windows Service installer.
- Extract downloaded file in your system.
- Ex: /home/cse/Desktop/apache-tomcat-9.0.4
Step-2 setting CLASSPATH & PATH
- open a terminal
- sudo gedit /etc/environment
- PATH=“/home/cse/Desktop/apach-tomcat-
9.0.4/bin:/home/cse/Desktop/jdk1.8.0_151/bin”
- CLASSPATH=“/home/cse/Desktop/apache-tomcat-9.0.4/lib/servlet-api.jar”
- Save a file and logout the system.
E.Swathi, CSE, CBIT
Step-3 start tomcat server
- startup.sh
Step-4 create a folder
- create a folder Ex ServletExamples.
- ServletExamples-> WEB-INF(capital letters), src (save
java files)
- WEB-INF-> classes folder(save .class files), web.xmlz

E.Swathi, CSE, CBIT


Step- 5 compile java program(servlet program)
javac FirstServlet.java
Step- 6 keep .class file in classes folder in WEB-INF.

Step- 7 configure web.xml


<?xml version="1.0" encoding="ISO-8859-1" ?> <web-app
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app> E.Swathi, CSE, CBIT
Step-8 create a war file in project folder (ServletExamples)
jar –cvf 123.war *

Step-9 open a browser


- type localhost:8080
- Select manager app
- Enter username and password.
Step-10 deploy a war file

Step-11 click a war file deployed in server

Step-12 type url pattern


http://localhost:8080/123/hello

E.Swathi, CSE, CBIT


Overview of Java Servlet API
• Servlet API consists of two important packages that encapsulates
all the important classes and interface, namely :
• javax.servlet package contains many interfaces and classes that
are used by the servlet or web container. These are not specific to
any protocol
• javax.servlet.http package contains interfaces and classes that are
responsible for http requests and http responses only.

E.Swathi, CSE, CBIT


Purpose of packages of Servlets

• Web container manage life cycle of servlets


• Implements application logic to serve client Http requests and
generate Http Response.
• Reads Http request and Http Response
• Deals with exceptions in servlets

E.Swathi, CSE, CBIT


The Servlet API
 Servlets are build from two packages:
 javax.servlet(Basic)
 javax.servlet.http(Advance)
 Servlet interface
 Implemented by all servlets
 Many methods invoked automatically by server
 Similar to applets (paint, init, start, etc.)
 abstract classes that implement Servlet
 GenericServlet (javax.servlet)
 HTTPServlet (javax.servlet.http)
 Examples in chapter extend HTTPServlet
 Methods
 void init( ServletConfig config )
 Automatically called, argument provided
The Servlet API
 Methods
 ServletConfig getServletConfig()
 Returns reference to object, gives access to config info
 void service ( ServletRequest request, ServletResponse response )
 Key method in all servlets
 Provide access to input and output streams
 Read from and send to client
 void destroy()
 Cleanup method, called when servlet exiting
Some Important Classes and Interfaces of javax.servlet

INTERFACES CLASSES
Servlet ServletInputStream
ServletContext ServletOutputStream
ServletConfig ServletRequestWrapper
ServletRequest ServletResponseWrapper
ServletResponse ServletRequestEvent
ServletContextListener ServletContextEvent
RequestDispatcher ServletRequestAttributeEvent
SingleThreadModel ServletContextAttributeEvent
Filter ServletException
FilterConfig UnavailableException
FilterChain GenericServlet
ServletRequestListener
E.Swathi, CSE, CBIT
• Interfaces and classes are grouped together based on their purpose and usage.
Purpose Class/interface
Servlet Implementation Javax.servlet.Servlet
SingleThreadModel,GenericServlet,
Javax.servlet.http.HttpServlet

Servlet Configuration javax.servlet.ServletConfig


Servlet Exceptions Javax.servlet.ServletException
Javax.servlet.UnavailableException
Requests and Response javax.servlet.http.HttpServletRequest,
javax.servlet.http.HttpServletRequestWapper,
javax.servlet.http.HttpServletResponse.
javax.servlet.ServletRequest,
javax.servlet.ServletResponse.
Session Tracking javax.servlet.http.HttpSession
Servlet Context javax.servlet.ServletContext,
Servlet Collabaration javax.servlet.RequestDispatcher
Filtering javax.servlet.Filter, FilterChain, FilterConfig.

E.Swathi, CSE, CBIT


Life Cycle of Servlet
servlet

GenericServlet HttpServlet

init(ServletConfig);

doGet(HttpServletRequest,
service(ServletRequest,
HttpServletResponse);
ServletResponse);
doPost(HttpServletRequest,
HttpServletResponse);
destroy(); …….
Life cycle of servlet
➢ Life cycle of the servlet describes how and when a servlet is loaded,
initialized and able to handle the requests and destroyed.
➢ Servlets are reside in the java virtual machine after they are loaded
and continue until server stops.
➢ Web server has module called servlet container to load and run
servlets
➢ Servlets consists of three methods during the life cycle of the java
servlet.
Loaded
Startup init()

Unloaded Initialized service()


Servicing

destroy()
Destroyed
E.Swathi, CSE, CBIT
Life cycle of servlets
➢ all these methods are in inteface javax.servlet.Servlet
1. loads the servlet class
2. create servlet instance
3. invokes init() method
4. Invokes service method
5. invokes destroy method
creation and initialization
➢ The servlets are created when a user first invokes a URL corresponding to
the servlet or servlets loaded when server starts up.
- loads servlet class
- create servlet instance
- initialize the servlet instance by calling the init() method
init() can be called only once in its life cycle by the following ways:
a) Through the ‘load-on-startup’ tag using the web.xml. This makes the servlet
to be loaded and initialized when the server starts.
b) Invoked only once before the service().
c) Initialize code like data base connections

E.Swathi, CSE, CBIT


service()
➢ this is the main method to process the client request.

➢ Servlet container invokes this method to process the request from client and
send back the formatted results to client

➢ Each request is serviced by a separate thread. The container calls the Service()
method of the servlet for every request.

➢ Service() method finds the HTTP request type and then calls
the appropriate request method such as doGet() or doPost().
- Public void doGet(HttpServletRequest req, HttpServletResponse res)throws
ServletException, IOException{ }

➢ Servlet container handles multiple request by sprawling multiple thread. Each


request assigned to one thread and each thread execute the service() method for
single instance of the servlet class.
destroy()
➢ this would called only once when the servlets are no longer needed.
➢ all the resources allocated to the servlet are released.
➢ Once it called the objects are marked to garbage collector.
➢ public void destroy() { }

E.Swathi, CSE, CBIT


Example (LifeCycle.java)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class LifeCycle extends GenericServlet
{
public void init()
{
System.out.println("init");
}
public void service(ServletRequest request, ServletResponse
response) throws ServletException, IOException
{
System.out.println("from service");
//PrintWriter out = response.getWriter();

E.Swathi, CSE, CBIT


// out.println("You are in service");
}
public void destroy()
{
System.out.println("destroy");
}
}
➢Follow the steps which are described in the gengreeting
example to execute this servlet

E.Swathi, CSE, CBIT


Servlet Implementation
classes/ interfaces used to implement servlets. To develop our own
servlets, we would implement one or more methods in these classes/
interfaces. When servlets are deployed, web container invoke these
methods to control life cycle, and execute the logic of servlets
Servlet Configuration
this interface provide access to initialization parameters that can be
configured while deploying a servlet. Every servlet associated with
ServletConfig object.
ServletExceptions
servlets throw two exceptions container performs the appropriate
error handling.
Request and Response
These objects provide methods to access, and underlying input
and output streams associated with the client connection. Using these
objects, we can read data from the input and write data back to the
client.

E.Swathi, CSE, CBIT


Servlet program
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException{
// Do required initialization
message = "Hello World";}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");}
public void destroy(){
// do nothing.}} E.Swathi, CSE, CBIT
1. javax.servlet.*;- this package provides all the classes and interfaces that
provide the framework in which the servlets operate.
➢ 2. javax.servlet.http.*;- provides classes and interfaces for working with
HTTP request and responses.
➢ the HttpServlet class provides the methods like doGet(), doPost() to
handle the particular type of methods.
➢ These methods are called by the default method called service(), which
identifies the what kind of request is being made and invoke that
appropriate method.

➢ The doGet() method accepts HttpServletRequest and


HttpServletResponse objects as arguments.
– HttpRequest object – incoming information to servlets
– HttpResponse object- outgoing information to the client
– Both methods throw ServletException and IOException.
• setContentType()- set the type of the response send by the server.

• Outgoing data is sent by using a PrintWriter object using println()


method and forwarded to the client.

• getWriter() used to obtain a PrintWriter object that can be used to write


character data to client.
E.Swathi, CSE, CBIT
Servlet interface
Public interface Servlet
- Specifies the contract between the we container and a servlet.
- Every servlet class must implement this interface directly or
indirectly.
- We always implement the interface indirectly by extending
either the javax.servlet.GenericServlet or
javax.servlet.http.HttpServlet classes.

E.Swathi, CSE, CBIT


javax.servlet.Servlet interface has five methods
1. p.v. init(ServletConfig config)
2. p.v. service ( ServletRequest req, ServletResponse Resp)
3. p.v. destroy()
4. p. ServletConfig getServletConfig()
5. p String getServletInfo()
1. p.v. init(ServletConfig config)
▪ init() method called by web container when servlets are instantiated
▪ performs any initialization required before being invoked against HTTP Requests.
2. service()
Entry point for executing logic in servlets. The container calls this method
in response to incoming requests.
3. destroy()
invoked before removing a servlet instance out of service
4. getServletConfig()
returns ServletConfig
5. getServletInfo()
Returns String object containing information about the servlet ( author,
creation date, description and so on).
E.Swathi, CSE, CBIT
The GenericServlet class
– Public abstract class GenericServlet implements Servlet, ServletConfig,
Serializable.
• Provides basic implementation of Servlet interface. This is an
abstract class, and all subclasses should implement the
service() method.
• additional methods are:
– public init()
– p.v log(String message): writes name of servlet and message argument
to web container.
– p.v. log(String mes, Throwable t): includes stack trace for Throwable
exception in addition to the servlet name and message.

E.Swathi, CSE, CBIT


The HttpServlet class
• HttpServlet class extends GenericServlet.
HttpServlet has following methods:
1. p.v service( ServletRequest req, ServletResponse res)
2. protected void service (HttpServletRequest req, HttpServletResponse res)
3. pr.v.doGet (HttpServletRequest req, HttpServletResponse res)
4. pr.v.doPost(HttpServletRequest req, HttpServletResponse res)
5. pr.v. doHead(HttpServletRequest req, HttpServletResponse res)
6. pr.v. doDelete(HttpServletRequest req, HttpServletResponse res)
7. pr.v. doOption(HttpServletRequest req, HttpServletResponse res)
8. pr.v. doPut(HttpServletRequest req, HttpServletResponse res)
9. pr.v. doTrace(HttpServletRequest req, HttpServletResponse res)
10. pr. Long getLastModified(HttpServletRequest req)

E.Swathi, CSE, CBIT


service () method
• The sequence of methods called when container receives a request
for a servlet
- public service()
- public service() calls the protected service() method after casting
arguments to HttpServletRequest and HttpServletResponse
respectively.
- protected service() calls one of the doXXX() methods depending on
type of the HTTP request method.
The getLastModified() method
this method returns the time that the servlet was last modified in
milliseconds since january 1, 1970.

E.Swathi, CSE, CBIT


Servlet Configuration
• javax.servlet.ServletConfig objects represent the configuration of a
servlet.
• Configuration information contains initialization parameters ( set of
name/ value pairs) the name of the servlet and a
javax.servlet.ServletContext object which gives the servlet
information about the container.
• The ServletConfig interface
- Specifies following methods
1. p String getInitParameter(String name)
2. p Enumeration getInitParameterNames()
3. p ServletContext getServletContext()
4. p String getServletName()

E.Swathi, CSE, CBIT


ServletConfig object is created per every servlet in web application by web
container.
- For every web application one servlet context is created.
- Web container creates ServletConfig at time of servlet object is created and
destroyed when servlets are destroyed
- Web container hand over this ServletConfig object by calling init() method and
pass ServletConfig object as argument to init method to Servlet object.
- Servlet class uses this object to get the configuration information of the servlet
such as servletname, init parameter values etc….
- Use case:
- suppose a servlet needs to access a database by provide username and
password. Every three months passwords to by changed.
- When I specify username and password in servlet programs I need to updated
in servlet program when password is changed. Again I have to recompile,
rebuild, redeploy etc… takes more time.
- To avoid such problems provide username and password in web.xml. By using
<init-param> tag in <servlet>

E.Swathi, CSE, CBIT


1. p String getInitParameter(String name)
- returns value of a named initialization parameter or null if the specified
parameter does not exist.
Web.xml
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
<init-param>
<param-name>email</param-name>
<param-value>xyz.cbit.ac.in</param-value>
</init-param> </servlet>
public class SimpleServlet extends GenericServlet
{
protected String myParam = null;
public void init(ServletConfig servletConfig) throws ServletException
{
this.myParam = servletConfig.getInitParameter(“email");
}

E.Swathi, CSE, CBIT


2. The getInitParameterNames()
returns an enumeration of all the initialization parameters of a
servlet.
3. getServletContext()
returns reference to the ServletContext object associated with
the web application.
4. getServletName()
public String getServletName()
returns name assigned to a servlet in its deployment descriptor
if no name assigned gives servlet class name

E.Swathi, CSE, CBIT


Obtain a reference to ServletConfig
1. During Servlet initialization
during initialization of Servlet the web container creates argument
type javax.servlet.ServletConfig and passes it to the init() method.
- In GenericServlet class, init() method is override, it should
explicitly invoke super.init() as follows

public intit(ServletConfig conf){


super.inti(config)
/// write initialization
}
2. Using the getServletConfig() method
- ServletConfig sc=getServletConfig();

E.Swathi, CSE, CBIT


Web.xml

• <web-app>
<servlet>
<init-param>
<param-name>AdminEmail</param-name>
<param-value>zulfiqar_mca@yahoo.co.in</param-value>
</init-param>

<init-param>
<param-name>Address</param-name>
<param-value>Okhla</param-value>
</init-param>

<init-param>
<param-name>PhoneNo</param-name>
<param-value>9911217074</param-value>
</init-param>

<servlet-name>Zulfiqar</servlet-name>
<servlet-class>InitServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/InitServlet</url-pattern>
</servlet-mapping>
</web-app> E.Swathi, CSE, CBIT
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*; Getparameters.java
import java.util.*;
public class InitServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

PrintWriter pw = response.getWriter();

pw.print("Init Parameters are : ");

Enumeration enumeration = getServletConfig().getInitParameterNames();

while(enumeration.hasMoreElements()){

pw.print(enumeration.nextElement() + " ");


}
pw.println("\nThe email address is " +
getServletConfig().getInitParameter("AdminEmail"));
pw.println("The address is " +
getServletConfig().getInitParameter("Address"));
pw.println("The phone no is " +
getServletConfig().getInitParameter("PhoneNo"));
}
}
E.Swathi, CSE, CBIT
Reading initialization parameters
➢ We can retreive the init parameter values which we have given
in the web.xml file.
➢ An object ServletConfig is created by the web container for
each servlet.
➢ The main job of the ServletConfig object is to give the init
parameters and also gives the servlet environment information.
To retrieve all the values of the init parameter use method
getInitParameterNames( ) which will return the Enumeration
of the init parameters.
<web-app>
<servlet>
<init-param> Web.xml
<param-name>AdminEmail</param-name>
<param-value>zulfiqar_mca@yahoo.co.in</param-value>
</init-param>
<init-param>
<param-name>Address</param-name>
<param-value>Okhla</param-value>
</init-param>
<init-param>
<param-name>PhoneNo</param-name>
<param-value>9911217074</param-value>
</init-param>
<servlet-name>Zulfiqar</servlet-name>
<servlet-class>InitServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Zulfiqar</servlet-name>
<url-pattern>/InitServlet</url-pattern>
</servlet-mapping>
</web-app>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*; Getparameters.java
import java.util.*;
public class InitServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

PrintWriter pw = response.getWriter();

pw.print("Init Parameters are : ");

Enumeration enumeration = getServletConfig().getInitParameterNames();

while(enumeration.hasMoreElements()){

pw.print(enumeration.nextElement() + " ");


}
pw.println("\nThe email address is " +
getServletConfig().getInitParameter("AdminEmail"));
pw.println("The address is " +
getServletConfig().getInitParameter("Address"));
pw.println("The phone no is " +
getServletConfig().getInitParameter("PhoneNo"));
}
}
Servlet Exceptions
• javax.servlet package specifies two exception classes
1. javax.servelt.ServletException
2. javax.servlet.UnavailableException

1. The ServletException class


- public class ServletException extends java.lang.Exception
- this exception thrown by init(), service(),doXXX() and destroy()
- public ServletException()
public ServletException(String msg)
2. UnavailableException class
- This exception indicate to the web container that the servlet is either temporarily or
permanently unavailable.
- public UnavailableException(String msg)
- public UnavailableExcption (String msg, int seconds)
int secondss specifies duration in seconds for which servlet is unavailable.

E.Swathi, CSE, CBIT


E.Swathi, CSE, CBIT
Request and Responses.
• These are the classes and interfaces for dealing with requests and
responses
• Javax.servlet.ServletRequest( I )
• javax.servlet.ServletResponse (i)
• javax.servlet.ServletInputStream( c)
• javax.servlet.ServletOutputStream( c)
• javax.servlet.http.HttpServletRequest (i)
• javax.servlet.http.HttpServletResponse (i)
• javax. servlet.http.HttpSevletRequestWrapper( c)
• javax .servlet.http.HttpServletResponseWrapper (c)
• javax.servlet.ServletRequestWrapper ©
• javax.servelt.ServletResponseWrapper ©

E.Swathi, CSE, CBIT


The ServletRequest Interface
web container creates an instance of ServletRequest object while calling
service() method of the GenericServlet or HttpServlet.
public interface ServletRequest

Method Description
public String getParameter(String name) Return value of a specified parameter
public String[] getParameterValues(String Returns array containing parameter values
key) Ex: checkbox
public Enumeration getParameterName() Enumeration of all the parameter names for
the request.
public Object getAttribute(String name) Value of named attribute
public Enumeration getAttributeNames() Enumeration of all the atrributes in the
request
public void setAttribute(String n, Object x) set named attribute
public void removeAttribute(String n) removes the named attribute from the
request
p ServletInputStream getInputStream() Access body of the request using
throws java.io.IOException ServletInputStream object
E.Swathi, CSE, CBIT
HttpServletReques Interface
• Provides methods to access request parameters
• public interface HttpServletRequest extends ServletRequest
method Description
public String getPathInfo() any extrea path information associate with
the request URL.
public String getPathTranslated() Extra path info into a real path
public String getQueryString() Query string associated with the request
public String getRequestURI URI path /myProject/myServlet/apress
public StringBuffer getRequestURL() protocol, server name, port and server path
public String getServletPath() Returns URI path associated with Servlet
public String getHeader(String name) Value of the named header from the HTTP
request
public String getMethod() Type of the HTTP Request method

E.Swathi, CSE, CBIT


ServletResponse Interface
• provides methods for constructing response from servlet.
• public interface ServletResponse
Methods Description
p.v setContentType(String type) Sets content type of the response
p.v setContentLenght( int size) Set the content length
p ServletOutputStream Writes binary data in the response
getOutputStream() throws
java.io.IOException
p.v setBufferSize(int size) sets the buffer size
p.v getBufferSize() get actual buffer size used for the
response

E.Swathi, CSE, CBIT


HttpServletResponse Interface
• The servlet can modify response headers and return results
through the HttpServletRequest object.
Method Description
p.v addCookie(Cookie c) add cookies
p.v.sendError( int status) To specify error pages with specifies status
code
p.v. setHeader(String s, string value) To set header name with specified value
p.v sendRedirect(String url) redirect client to url

E.Swathi, CSE, CBIT


HttpServlet methods

Handling HTTP Requests and Responses

✓The HttpServlet class provides specialized methods that


handle the various types of HTTP requests

✓The GET and POST requests are commonly used when


handling form input
67
E.Swathi, CSE, CBIT
Handling HTTP GET Requests
✓Here we will develop a servlet that handles an HTTP GET
request
<html> (ColorGet.html)
<body>
<center>
<form name="Form1“ method=“get”
action=" Color">
<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>
68
E.Swathi, CSE, CBIT
</center> </body></html>
(ColorGetServlet.java)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}

69
E.Swathi, CSE, CBIT
✓Follow the steps which are described in the gengreeting
example and then
1.Start Tomcat (if it is not already running)
2.Display the Web page (ColorGet.html) in a browser

3.Select a color

70
E.Swathi, CSE, CBIT
4.Submit the Web page. The browser will display the
response that is dynamically generated by the servlet

71
E.Swathi, CSE, CBIT
✓Parameters for an HTTP GET request are included as part
of the URL that is sent to the Web server

✓The characters to the right of the question mark are known


as the query string
Handling HTTP POST Requests
✓Here we will develop a servlet that handles an HTTP
POST request
<html> (ColorPost.html)
<body>
<center>
<form name="Form1" "/colorpostservlet/Cpost"
method="post"
action="http://localhost:8080/colorpostservlet/Cpost">
<B>Color:</B>
<select name="color" size="1">
72
E.Swathi, CSE, CBIT
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</center>
</body>
</html>
(ColorPostServlet.java)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String color = request.getParameter("color"); 73
E.Swathi, CSE, CBIT
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
✓Follow the steps which are described in the gengreeting
example and then
1.Start Tomcat (if it is not already running)
2.Display the Web page (ColorPost.html) in a browser

74
E.Swathi, CSE, CBIT
3.Select a color

4.Submit the Web page. The browser will display the


response that is dynamically generated by the servlet

75
E.Swathi, CSE, CBIT
✓Parameters for an HTTP POST request are not included as
part of the URL that is sent to the Web server

✓The parameter names and values are sent in the body of


the HTTP request

76
E.Swathi, CSE, CBIT
Servlet Sessions, Context and Collaboration:
Approaches to Session tracking,
Session Tracking with java servlet API,
Servlet Context,
Servlet Collaboration.
ServletContext Interface
1. For every web application web container creates one
ServletContext object to hold application level configuration
information such as request dispatcher, servlet API version, servler
version.
2. ServletContext created at time of application deployment and
destroyed at time of application undeployment
3. ServletContext object create by calling below methods
ServletContex context= config.getServletContext(); or
ServletContex context= getServletContext();
USE CASE
- when servlet in an web application required to access a database by
using username and password. Provide this information in web.xml
rather than in every servlet program.

E.Swathi, CSE, CBIT


E.Swathi, CSE, CBIT
Methods in ServletContext interface
Methods Description
public String getInitParameter(String Returns the parameter value for the
name) specified parameter name.
public Enumeration Returns the names of the context's
getInitParameterNames( initialization parameters.
public void setAttribute(String sets the given object in the application
name,Object object) scope.
public Enumeration Returns the names of the context's
getInitParameterNames() initialization parameters as an
Enumeration of String objects.
public void removeAttribute(String Removes the attribute with the given
name): name from the servlet context.
public URL getResource(String path) URL to a resource at the specified path
p requestDispatcher Return requestDispatcher object
getRequestDispatcher()
p String getServlerInfo() Server info
getServletContextName() Returns context name
getMajorVersion(), getMinorVersion() Servlet API version.
E.Swathi, CSE, CBIT
How context param is initialized in web.xml

E.Swathi, CSE, CBIT


<web-app>
<servlet> Web.xml
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
<context-param>
<param-name>username</param-name>
<param-value>system</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>oracle</param-value>
</context-param>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>
E.Swathi, CSE, CBIT
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException {
res.setContentType("text/html");
PrintWriter out=res.getWriter();
ServletContext context=getServletContext();
Enumeration<String> e=context.getInitParameterNames();
String str="";
while(e.hasMoreElements()){
str=e.nextElement();
out.print("<br> "+context.getInitParameter(str));
}
}}

E.Swathi, CSE, CBIT


Attributes in servlet
• An attribute in servlet is an object that can be set, get or
removed from one of the following scopes:
• request scope
• session scope
• application scope
• The servlet programmer can pass informations from one
servlet to another using attributes. It is just like passing object
from one class to another so that we can reuse the same object
again and again.

E.Swathi, CSE, CBIT


E.Swathi, CSE, CBIT
Session tracking
➢ Session means simply a particular time of interval
➢ Session tracking is way to maintain the state of the user.
➢ Session tracking is used to identify the user.
➢ Session means server should be able to identify that a
series of requests from a single client form a working
session.
➢ State means server should be able to remember
information related to previous requests
➢ Shopping cart or the online bank applications can
distinguish one user from another.

E.Swathi, CSE, CBIT


Session Management
There are basically 2 types of web-applications
1. Stateless web application
2. Statefull web application

1. Stateless web application:


In these web applications, whenever the client sends a request to the server,
the server process the request, generate the response and send s it to the
client and forget about that client. Any subsequent requests will be treated in
the same manner. These type of applications are called fire and forget
applications

E.Swathi, CSE, CBIT


1. State full web application:
In these web applications, whenever the client sends a request to the server,
the server process the request, generate the response and remember the
client. If the client sends the second request he will be remembered back by
the server.
Ex:
shopping cart
In this application the scenario is as follows:
• The user goes to a shopping site and a catalog is presented to the user
• The user selects an item from the catalog and clicks the button “add to cart”
• The servlet maintains a cart for the user when the add to cart is selected, the
currently chosen item from the catalog is added to the cart
• This process of selecting from catalog and adding to the cart may repeat
several times
• Even though there are multiple requests and responses, the servlet will have
to maintain a state across all these interactions. The state in this case is the
shopping cart.
In this scenario the servlet cannot forget what happened in the previous
transaction

E.Swathi, CSE, CBIT


cookies
• Cookies are small piece of information
persisted among multiple client requests

E.Swathi, CSE, CBIT


Session Management:
The scenario for implementation of the session management is as follows:
1. When the first time the request( add to cart) goes to the servlet, the servlet will
generate a unique session-id .This session-id is a 128 bit no.
2. This id is sent by the servlet to the browser, along with the first response
3. The browser will receive this session-id and maintain the it in the table. Every session-
id is associated with a URL
4. Next time, when the user sends the second request (add to cart), the browser will
automatically sends the session-id along with the request
5. The servlet will now receive the session-id and depend on that it identifies the
shopping cart for the user

To send the session-id to the client side we have the following ways
1. Cookies
2. URL rewriting
3. HTTP session
4. Hidden form field.

E.Swathi, CSE, CBIT


Session tracking methods
1. User Authentication

2.Cookies

3. URL Rewriting

4. Hidden form fields

5. HTTP Session.
above methods are differ in implementation details

1. User Authentication
▪ User must be authorized first.
▪ When user want to access the web site he must provide user name and
password on login page.
▪ Based on authentication details server maintains the session.
▪ Doesn’t work well if user logged in from different browsers.
E.Swathi, CSE, CBIT
Cookies: A cookie is a concatenation of name, value pairs separated by
semicolon(;) and as optional attributes like comments, domain qualifiers ,
maximum age and its version.
EX:
if the session-id is 35248972
The cookie looks as follows
Jsessionid=35248972; encryption=false; expiry=30

E.Swathi, CSE, CBIT


Using Cookies

Let’s develop a servlet that illustrates how to use cookies


(AddCookie.html)
<html>
<body>
<center>
<form name="Form1"
method="post"
action="Add">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">

E.Swathi, CSE, CBIT


<input type=submit value="Submit">
</form>
</center>
</body>
</html>
(AddCookieServlet.java)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Get parameter from HTTP request.
String data = request.getParameter("data");
// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);
// Add cookie to HTTP response.
E.Swathi, CSE, CBIT
response.addCookie(cookie);
// Write output to browser.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
}
}
(GetCookiesServlet.java)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Get cookies from header of HTTP request.
E.Swathi, CSE, CBIT
Cookie[] cookies = request.getCookies();
// Display these cookies.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name +
"; value = " + value);
}
pw.close();
}
}
(Web.xml)
<web-app>
<servlet>
<servlet-name>add</servlet-name> E.Swathi, CSE, CBIT
<servlet-class>AddCookieServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>gcs</servlet-name>
<servlet-class>GetCookiesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>add</servlet-name>
<url-pattern>/Add</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>gcs</servlet-name>
<url-pattern>/Getcs</url-pattern>
</servlet-mapping>
</web-app>

E.Swathi, CSE, CBIT


✓Follow the steps which are described in the gengreeting
example and then
1.Start Tomcat (if it is not already running)
2.Display the Web page (AddCookie.html) in a browser

3.Enter a value for MyCookie

E.Swathi, CSE, CBIT


4.Submit the Web page

5.Next, request the following URL via the browser:


http://localhost:8080/addcookie/Getcs Alias of GetCookiesServlet

E.Swathi, CSE, CBIT


cookies
• Advantages
- Easy to implement
- Persist even after the system shutdown
- All web servers supports cookies.
limitations\
- When the client disable cookies on his machine due to security issues the
session management is not possible with cookies
- The number of cookies support by the browser is fixed.
- The size of the cookie is also fixed . So not possible to hold huge amount of
information.

E.Swathi, CSE, CBIT


index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/>
<br/>
<input type="submit" value="go"/>
</form>

E.Swathi, CSE, CBIT


import java.io.*;
import javax.servlet.*; FirstServlet.java
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie object


response.addCookie(ck);//adding cookie in the response
//creating submit button
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
E.Swathi, CSE, CBIT
import java.io.*;
import javax.servlet.*; SecondServlet.java
import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {


public void doPost(HttpServletRequest request, HttpServletResponse
response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();

}catch(Exception e){System.out.println(e);}
}

E.Swathi, CSE, CBIT


<web-app>
<servlet>
<servlet-name>s1</servlet-name>
web.xml
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>

E.Swathi, CSE, CBIT


Session tracking- URL Rewriting
➢ If user disabled cookies, other method to track session is URL Rewriting.
➢ Extra information is added at end of every URL used to keep track of the
session.
➢ Requested URL is modified to include session id.
➢ Origal url: www.javatutorials.com/index.html/..
➢ Rewritten url: www.javatutorials.com/index.html?Jsessionid=2779
➢ the session id is attached as Jsessionid=2779 which can be accessed at the
web server to identify the client
➢ Drawback
➢ It is very difficult to rewrite every URL present in response.
➢ It works only for the dynamic documents.
- It is recommended to use both URL rewriting and cookies simultaneously.

E.Swathi, CSE, CBIT


E.Swathi, CSE, CBIT
3. Hidden Form fields
➢ A web server can send a hidden HTML form field along with a
unique session ID as follows to store the client state.

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

➢In this case Hidden form field is used to maintain the state of the user.

➢These fields are not visible directly to the user.

➢This is not secure, User can viewed using view source option from the
browsers .
➢Not able to maintain the state of an end user when it encounters a
static document.

E.Swathi, CSE, CBIT


Hidden form field

<form action="http://www.google.com">// when u click

Hello ! <input type="hidden" name="user" value=“CBIT">

<input type="Submit" value="Click Here">

</form>

When u click the button click Here google.com page is displayed.


E.Swathi, CSE, CBIT
Session Tracking
✓HTTP is a stateless protocol. Each request is independent
of the previous one

✓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 mechanism

✓The following servlet (DateServlet.java) illustrates how to


use session state
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
E.Swathi, CSE, CBIT
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Get the HttpSession object.
HttpSession hs = request.getSession(true);
// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
// Display date/time of last access.
Date date = (Date)hs.getAttribute("date");
if(date != null) {
pw.print("Last access: " + date + "<br>");
}
// Display current date/time.
date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);
}} E.Swathi, CSE, CBIT
1.Start Tomcat (if it is not already running)

2.When you first request this servlet, the browser displays


one line with the current date and time information

3.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
E.Swathi, CSE, CBIT
E.Swathi, CSE, CBIT
HttpSession interface
• Servlet container creates a session id for every user to identify a
user across multiple requests.
• HttpSession object is created by using two methods
1. HttpSession session=request.getSession(): returns HttpSession
object associated with this request. If session does not exist create
a new session
2. HttpSession session= request.getSession( boolean true):
returns HttpSession object associated with request if no session
exist creates a Session true and returns the Session object.

E.Swathi, CSE, CBIT


Methods in HttpSession
1. getId() Returns a string containing the unique
identifier assigned to this session.

2. getCreationTime() Returns the time when this session was


created, measured in milliseconds since
midnight January 1, 1970 GMT.

3. getLastAccessedTime(): Returns the last time the client sent a


request associated with this session

4. invalidate() Invalidates this session then unbinds any


objects bound to it

5. getAttribute(String name) Returns the object bound with the


specified name in this session

E.Swathi, CSE, CBIT


import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get the HttpSession object.
HttpSession session = request.getSession(true);
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this web page.
Date lastAccessTime = new Date(session.getLastAccessedTime());
// Set response content type
response.setContentType("text/html"); PrintWriter out = response.getWriter();
out.print(“id: " + session.getId() + "<br>");
out.print(“last access time:” + lastAccessTime+”<br>”);
Out.print(“creation time:” + createTime+ “<br>”);
}
}

E.Swathi, CSE, CBIT


1.Start Tomcat (if it is not already running)

2.When you first request this servlet, the browser displays


Following information

Reload page

E.Swathi, CSE, CBIT


Servlet Collaboration

• Servlet collaboration also called Servlet inter communication


• Servlet collaboration means one servlet can forward its request
to another servlet.
• Servlet collaboration done in different ways
1. getServlet() // this method is deprecated
2. RequestDispatcher object
3. sendRedirect()

E.Swathi, CSE, CBIT


RequestDispatcher interface
• It is one of the way of servlet collaboration.

• The RequestDispatcher interface provides the facility of dispatching


the request to another resource it may be html, servlet or jsp.
• This interface can also be used to include the content of another
resource also.
Creation of RequestDispatcher object
- e getRequestDispatcher() method of ServletRequest interface returns
the object of RequestDispatcher.
- Syntax:
- RequestDispatcher rd=request.getRequestDispatcher("servlet2");
- // servlet2 is url-pattern of second servlet

E.Swathi, CSE, CBIT


Methods in RequestDispatcher interface
• Two methods in RequestDispatcher interface
1 public void forward(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException:
Forwards a request from a servlet to another resource (servlet, JSP file, or
HTML file) on the server.

Response of first servlet is not displayed on browser only second servelt response is
send to client
E.Swathi, CSE, CBIT
2. public void include(ServletRequest
request,ServletResponse response)throws
ServletException,java.io.IOException:
Includes the content of a resource (servlet, JSP page, or HTML
file) in the response.

response of second servlet is included in the response of the first servlet that is being
sent to the client.

E.Swathi, CSE, CBIT


Example on RequestDispatcher
• Aim: write a servlet program to demonstrate RequestDispatcher
which includes forward and include methods.
• Description: we are validating the password entered by the user. If
password is validated, it will forward the request to the
WelcomeServlet, otherwise will show an error message: sorry
username or password error!. 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
password is servet, 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.

E.Swathi, CSE, CBIT


E.Swathi, CSE, CBIT
Introduction to Filters

• Filter is an object which is invoked to preprocessing and post


processing of request .
• They are preprocessors of the request before it reaches a
servlet, and/or postprocessors of the response leaving a servlet.
• Request to a servlets are processed by the filters and then
forward to a requested resources.
• Filters are not servlets.
• A chain of filters are created for a single resource .
• Entry to a filters are defined in web.xml (Deployment
description file)

E. Swathi, CSE, CBIT


Advantages of Filters
1. Authentication and authorization of request for a resource
2. Compress the response data sent to the client
3. Alters the response of the server by adding some cookies,
header information etc.
4. Encryption and decryption of data
5. Logging the user requests into a log file
6. Records the incoming requests.

E. Swathi, CSE, CBIT


Filter API
• Filters are implemented by the package javax.servlet.Filter
interface.
• Filter API has following interfaces
1. javax.servlet.Filter
- every filter class must implement this
2. javax.servlet.FilterConfig
3. javax.servlet.FilterChain

E. Swathi, CSE, CBIT


javax.servlet.Filter
- this interface provides life cycle methods
methods in Filter interface
1. Public void init(FilterConfi fc) throws ServletException
- init() method is invoked only once. It is used to initialize the filter.
- container sends configuration information ( initilization
parameters) to the filter via a FilterConfig object
- similar to ServletConfig object
2. Public void doFilter(ServletRequest reg, ServletResponse
res,FilterChain chain) throws IOException,ServletException
- instructs the container to process the rest of the filters.
3. Public void destroy()
- removes the filters from out of service.

E. Swathi, CSE, CBIT


javax.servlet.FilterConfig
provide access to configuration information like filter name,
initialization parameters.
methods in FilterConfig interface
1. Public void getFilterName()// returns filter name specified in
web.xml
2. Public String getInitparameter(string name);
3. public Enumeration getIntParameterNames()
4. public ServletContext getServletContext()

E. Swathi, CSE, CBIT


javax.servlet.FilterChain
using this interface FilterChain, the filter can let the container to
invoke the next filter in the chain or resource.
- It has a single method
- public void doFilter(ServletRequest req, ServletResponse res)

E. Swathi, CSE, CBIT


Example on Filters
• We can perform authentication in filter. Here, we are going to
check to password given by the user in filter class, if given
password is admin, it will forward the request to the
WelcomeAdmin servlet otherwise it will display error
message.
• 4 files are needed
• index.html
• MyFilter.java
• AdminServlet.java
• web.xml

E. Swathi, CSE, CBIT


// index.html
<form action="servlet1">
Name:<input type="text" name="name"/><br/>
Password:<input type="password" name="password"/><br/>

<input type="submit" value="login">

</form>

E. Swathi, CSE, CBIT


//MyFilter.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
public class MyFilter implements Filter{
public void init(FilterConfig arg0) throws ServletException {}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
PrintWriter out=resp.getWriter();
String password=req.getParameter("password");
if(password.equals("admin")){
chain.doFilter(req, resp);//sends request to next resource
} else{
out.print("username or password error!");
RequestDispatcher rd=req.getRequestDispatcher("index.html");
rd.include(req, resp);
} }
public void destroy() {} } E. Swathi, CSE, CBIT
//AdminServlet.java (servlet class)
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.*;

public class AdminServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter(“name”);

out.print("welcome to “+name);
out.close();
}
}

E. Swathi, CSE, CBIT


//web.xml
<web-app>
<servlet>
<servlet-name>AdminServlet</servlet-name>
<servlet-class>AdminServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>AdminServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<filter> Go to Folder Filters


<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>

</web-app>
E. Swathi, CSE, CBIT
References

• https://way2java.com/java-general/introduction-to-2-tier-and-
3-tier-architecture/
• https://way2java.com/
• https://www.studytonight.com/servlet/servlet-api.php

E.Swathi, CSE, CBIT

You might also like