0% found this document useful (0 votes)
4 views132 pages

Understanding Java Servlets Basics

The document provides an overview of Java Servlets as part of Advanced Java programming, detailing the differences between Core and Advanced Java, the servlet model, lifecycle, and HTTP methods. It explains the importance of servlets in creating dynamic web applications, their tasks, and advantages. Additionally, it covers servlet structure, deployment descriptors, and the use of various HTTP methods for handling client requests.

Uploaded by

cegipe7927
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)
4 views132 pages

Understanding Java Servlets Basics

The document provides an overview of Java Servlets as part of Advanced Java programming, detailing the differences between Core and Advanced Java, the servlet model, lifecycle, and HTTP methods. It explains the importance of servlets in creating dynamic web applications, their tasks, and advantages. Additionally, it covers servlet structure, deployment descriptors, and the use of various HTTP methods for handling client requests.

Uploaded by

cegipe7927
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

Java Servlets

Advanced Java Programming(3160707)


By: Dr. Saurabh S. Tandel
Assistant Professor,
Computer Engineering Department, CKPCET, Surat
[Link]@[Link]
Outline
❖ Core Java Vs. Advanced Java
❖ Why Advanced Java?
❖ Servlet Model: Overview of Servlet
❖ Servlet Life Cycle
❖ HTTP Methods, Structure and Deployment Descriptor
❖ ServletContext and ServletConfig interface
❖ Attribute in Servlet
2
Outline(Cont...)
❖ Request Dispatcher interface
❖ The Filter API: Filter, FilterChain, Filter Config
❖ Cookies and Session Management: Understanding state and
session, Understanding Session Timeout and Session
Tracking
❖ URL Rewriting

3
Core Java
Vs.
Advanced Java
4
Core Java Vs. Advanced Java
❖ Core Java: Core Java is the part of Java programming language that
is used for creating or developing a general-purpose application.
❖ Advanced Java: Advanced Java is also a part of Java programming
language that generally deals with online application like the
website and mobile application.

5
Core Java Vs. Advanced Java(Cont...)
Core Java Advanced Java

To develop general purpose applications. To develop online application and mobile application.

Without Core Java, no one can develop Whereas advanced java only deals with some
any advanced java applications. specialization like Database, DOM(web), networking etc.

Important Concepts: OOP, data types, Apart from the core java parts, it has some specific
operators, functions, loops, exception sections like database connectivity, web services,
handling, threading etc. servlets etc.

It uses only one tier architecture that is It uses two tier architecture i.e. client side architecture
why it is called as ‘stand alone’ application. and server side or backend architecture.

Core java programming covers the swings, Advance java is used for web based application and
socket, awt, thread concept, collection enterprise application.
object and classes.

6
Why Advanced Java?

7
Why Advanced Java?
❖ Advanced Java i.e. JEE (Java Enterprise Edition) gives you the library to
understand the Client-Server architecture for Web Application Development.
❖ You will be able to work with Web and Application Servers like Apache
Tomcat, Glassfish etc and understand the communication over HTTP
protocol.
❖ There are lot of Advance Java frameworks like Spring, JSF, Struts etc. which
enable you to develop a secure transaction based web apps for the domains
like E-Commerce, Banking, Legal, Financial, Healthcare, Inventory etc.

8
Why Advanced Java?(Cont...)
❖ Learning Advanced Java also enables you to work with ORM
(Object relational Mapping) tools like Hibernate(Open Source),
MyBatis(Apache), Toplink(Oracle) for successfully working
with several RDBMS like Oracle, MySQL, SQL-Server etc.
❖ To work and understand the hot technologies like Hadoop and
Cloud services, you should be prepared with Core and Advance
Java concepts.

9
Servlet Model:
Overview of Servlet

10
Servlet Model: Overview of Servlet
What is a Servlet?

❖ Servlet technology is used to create a web application (resides at


server side and generates dynamic web pages).
❖ Is robust and scalable because of java language.
❖ Before Servlet, CGI (Common Gateway Interface) scripting
language was common as a server-side programming language &
there were many disadvantages to this technology.
11
Servlet Model: Overview of Servlet(Cont...)
What is a Servlet?

❖ A Java programming language class used to extend the capabilities


of servers by means of a request-response programming model.
❖ Servlets can respond to any type of request, they are commonly
used to extend the applications hosted by web servers.
❖ For such applications, Java Servlet technology defines
HTTP-specific servlet classes.
12
Servlet Model: Overview of Servlet(Cont...)
What is a Servlet(Summary)?
❖ A technology which is used to create a web application.
❖ Is an API that provides many interfaces and classes including
documentation.
❖ Is an interface that must be implemented for creating any Servlet.
❖ Is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
❖ A web component that is deployed on the server to create a dynamic web
page.
13
Servlet Architecture

Fig.1: Servlet Architecture


14
Servlet Tasks
Servlets perform the following major tasks −

❖ Read the explicit data sent by the clients (browsers). This


includes an HTML form on a Web page or it could also come from
an applet or a custom HTTP client program.
❖ Read the implicit HTTP request data sent by the clients
(browsers). This includes cookies, media types and compression
schemes the browser understands, and so forth.
15
Servlet Tasks(Cont...)
❖ Process the data and generate the results. This process may
require talking to a database, executing an RMI or CORBA call,
invoking a Web service, or computing the response directly.
❖ Send the explicit data (i.e., the document) to the clients
(browsers). This document can be sent in a variety of formats,
including text (HTML or XML), binary (GIF images), Excel, etc.

16
Servlet Tasks(Cont...)
❖ Send the implicit HTTP response to the clients (browsers). This
includes telling the browsers or other clients what type of
document is being returned (e.g., HTML), setting cookies and
caching parameters, and other such tasks.

17
Advantages of using Servlets
❖ Less response time because each request runs in a separate
thread.
❖ Servlets are scalable.
❖ Servlets are robust and object oriented.
❖ Servlets are platform independent.

18
Servlet Life Cycle

19
Servlet Life Cycle
A servlet life cycle can be defined as the entire process from its creation
till the destruction. The following are the paths followed by a servlet.

❖ The servlet is initialized by calling the init() method.


❖ The servlet calls service() method to process a client's request.
❖ The servlet is terminated by calling the destroy() method.
❖ Finally, servlet is garbage collected by the garbage collector of the
JVM.

20
Servlet Life Cycle - Architecture

Fig.2: Servlet Life Cycle - Architecture 21


Servlet Life Cycle - Architecture(Cont...)
The figure in the last slide depicts a typical servlet life-cycle scenario.

❖ First the HTTP requests coming to the server are delegated to the servlet
container.
❖ The servlet container loads the servlet before invoking the service()
method.
❖ Then the servlet container handles multiple requests by spawning
multiple threads, each thread executing the service() method of a single
instance of the servlet.
22
Servlet Life Cycle - init() Method
❖ The init method is called only once. It is called only when the
servlet is created, and not called for any user requests afterwards.
So, it is used for one-time initializations, just as with the init
method of applets.
❖ The servlet is normally created when a user first invokes a URL
corresponding to the servlet, but you can also specify that the
servlet be loaded when the server is first started.
23
Servlet Life Cycle - init() Method(Cont...)
❖ When a user invokes a servlet, a single instance of each servlet gets
created, with each user request resulting in a new thread that is handed
off to doGet or doPost as appropriate. The init() method simply creates or
loads some data that will be used throughout the life of the servlet.

The init method definition looks like this −

public void init() throws ServletException {


// Initialization code...
}
24
Servlet Life Cycle - service() Method
❖ The service() method is the main method to perform the actual
task.
❖ The servlet container (i.e. web server) calls the service() method
to handle requests coming from the client (browsers) and to write
the formatted response back to the client.
❖ Each time the server receives a request for a servlet, the server
spawns a new thread and calls service.
25
Servlet Life Cycle - service() Method(Cont...)
❖ The service() method checks the HTTP request type (GET, POST,
PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc.
methods as appropriate.

Here is the signature of this method −


public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
}

26
Servlet Life Cycle - service() Method(Cont...)
❖ The service() method is called by the container and service() method
invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate.
❖ So you have nothing to do with service() method but you override
either doGet() or doPost() depending on what type of request you
receive from the client.
❖ The doGet() and doPost() are most frequently used methods within
each service request.
❖ Here is the signature of these two methods.(Next Slide)
27
Servlet Life Cycle - service() Method(Cont...)
The doGet() Method

❖ A GET request results from a normal request for a URL or from an


HTML form that has no METHOD specified and it should be
handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Servlet code
}
28
Servlet Life Cycle - service() Method(Cont...)
The doPost() Method

❖ A POST request results from an HTML form that specifically lists


POST as the METHOD and it should be handled by doPost()
method.

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Servlet code
}
29
Servlet Life Cycle - destroy() Method
❖ The destroy() method is called only once at the end of the life cycle
of a servlet.
❖ This method gives your servlet a chance to close database
connections, halt background threads, write cookie lists or hit
counts to disk, and perform other such cleanup activities.
❖ After the destroy() method is called, the servlet object is marked
for garbage collection.
30
Servlet Life Cycle - destroy() Method(Cont...)
destroy method definition looks like this −
public void destroy() {
// Finalization code...
}

31
HTTP Methods, Structure
& Deployment Descriptor

32
GET Method
❖ The GET method sends the encoded user information appended to
the page request. The page and the encoded information are
separated by the ? (question mark) symbol as follows −

[Link]

❖ The GET method is the default method to pass information from


browser to web server and it produces a long string that appears
in your browser's Location:box.
33
GET Method(Cont...)
❖ Never use the GET method if you have password or other sensitive
information to pass to the server. The GET method has size
limitation: only 1024 characters can be used in a request string.
❖ This information is passed using QUERY_STRING header and will
be accessible through QUERY_STRING environment variable and
Servlet handles this type of requests using doGet() method.

34
POST Method
❖ A generally more reliable method of passing information to a backend
program is the POST method.
❖ This packages the information in exactly the same way as GET
method, but instead of sending it as a text string after a ? (question
mark) in the URL it sends it as a separate message.
❖ This message comes to the backend program in the form of the
standard input which you can parse and use for your processing.
❖ Servlet handles this type of requests using doPost() method.
35
Reading Form Data using Servlet
Servlets handle form data parsing automatically using the following methods
depending on the situation −

❖ getParameter() − You call [Link]() method to get the


value of a form parameter.
❖ getParameterValues() − Call this method if the parameter appears more
than once and returns multiple values, for example checkbox.
❖ getParameterNames() − Call this method if you want a complete list of
all parameters in the current request.
36
GenericServlet Vs. HttpServlet
❖ The main difference between GenericServlet and HttpServlet is
that the GenericServlet is protocol independent and can be used
with any protocol such as HTTP, SMTP, FTP, and, CGI while
HttpServlet is protocol dependent and only used with HTTP
protocol.
❖ Preferred is HttpServlet because of its advancedness over
GenericServlet.
37
Basic Servlet Structure
❖ Next slide example outlines a basic servlet that handles GET requests.
❖ GET requests are the usual type of browser requests for Web pages.
❖ A browser generates this request when the user enters a URL on the
address line, follows a link from a Web page, or submits an HTML form
that either does not specify a METHOD or specifies METHOD="GET".
❖ Servlets can also easily handle POST requests, which are generated
when someone submits an HTML form that specifies METHOD="POST".

38
Basic Servlet Structure(Cont...)
import [Link].*;

import [Link].*;

import [Link].*;

public class ServletTemplate extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Use "request" to read incoming HTTP headers

// (e.g., cookies) and query data from HTML forms.

// Use "response" to specify the HTTP response status

// code and headers (e.g. the content type, cookies).

PrintWriter out = [Link]();

// Use "out" to send content to browser. } }


39
Basic Servlet Structure(Cont...)
❖ To be a servlet, a class should extend HttpServlet and override doGet or
doPost, depending on whether the data is being sent by GET or by POST.
❖ If you want a servlet to take the same action for both GET and POST
requests, simply have doGet call doPost, or vice versa.
❖ Both doGet and doPost take two arguments: an HttpServletRequest and
an HttpServletResponse. The HttpServletRequest has methods by which
you can find out about incoming information such as form (query) data,
HTTP request headers, and the client's hostname.
40
Basic Servlet Structure(Cont...)
❖ The HttpServletResponse lets you specify outgoing information such as HTTP
status codes (200, 404, etc.) and response headers (Content-Type, Set-Cookie,
etc.). Most importantly, it lets you obtain a PrintWriter with which you send the
document content back to the client. For simple servlets, most of the effort is
spent in println statements that generate the desired page.
❖ Since doGet and doPost throw two exceptions, you are required to include them
in the declaration. Finally, you must import classes in [Link] (for PrintWriter,
etc.), [Link] (for HttpServlet, etc.), and [Link] (for
HttpServletRequest and HttpServletResponse).
41
Servlet - Deployment Descriptor
❖ It is an xml file which acts as a mediator between a web
application developer and a web container.
❖ It is also called Deployment Descriptor File.
❖ Note: we can not change the directory or extension name of this
[Link] because it is standard name to be recognized by container
at run-time.

42
Servlet - Deployment Descriptor(Cont...)

Fig.3: Servlet - Deployment Descriptor file


43
Servlet - Deployment Descriptor(Cont...)
In [Link] file, we configure the following

❖ Servlet
❖ JSP
❖ Filter
❖ Listeners
❖ Welcome files
❖ Security, etc...
44
Servlet - Deployment Descriptor(Cont...)
To configure a servlet file we need the following two xml tag.

❖ <Servlet>
❖ <Servlet-mapping>
❖ <servlet>: tags are used to configure the servlet, within this tag
we write Servlet name and class name.
❖ <Servlet-mapping>: tags are used to map the servlet to a URL .

45
Servlet - Deployment Descriptor(Cont...)
The structure of [Link] files is already defined by sun MicroSystem.
So as a developer we should follow the structure to develop the
configuration of web resources.

While configuring a servlet in [Link], three names are added for it.

❖ Alias name or register name


❖ Fully qualified class name
❖ url-pattern
46
Servlet - Deployment Descriptor(Cont...)
Syntax:
<web-app>

<servlet>

<servlet-name>alias name</servlet-name>

<servlet-class>fully qualified class name</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>alias name</servlet-name>

<url-pattern>/url pattern</url-pattern>

</servlet-mapping>

</web-app>

47
ServletContext &
ServletConfig Interface

48
ServletConfig Interface
❖ Servlet Container creates ServletConfig object for each Servlet
during initialization, to pass information to the Servlet.
❖ This object can be used to get configuration information such as
parameter name and values from deployment descriptor
file([Link]).

49
Methods of ServletConfig Interface
❖ public String getInitParameter(String name): Returns the value of given
parameter as String, or null if the given parameter doesn’t exist in [Link].
❖ public Enumeration getInitParameterNames(): Returns an enumeration
of all the parameter names.
❖ public String getServletName(): Returns the name of the servlet instance.
❖ public ServletContext getServletContext(): Returns an object of
ServletContext.

50
Example of ServletConfig Interface
❖ In this example(On the Next Slide), we will use two methods
getInitParameter() and getInitParameterNames() to get all the
parameters from [Link] along with their values.
❖ The getInitParameterNames() method returns an enumeration of
all parameters names and by passing those names during the call
of getInitParameter() method, we can get the corresponding
parameter value from [Link].
51
Example of ServletConfig Interface(Cont...)
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
public class DemoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
[Link]("text/html;charset=UTF-8");
PrintWriter pwriter = [Link]();
52
Example of ServletConfig Interface(Cont...)
ServletConfig sc=getServletConfig();
Enumeration<String> e=[Link]();
String str;

while([Link]()) {
str=[Link]();
[Link]("<br>Param Name: "+str);
[Link](" value: "+[Link](str));
}
}
} 53
Example of ServletConfig Interface(Cont...)
[Link] Code:
<web-app>
<display-name>BeginnersBookDemo</display-name>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>

54
Example of ServletConfig Interface(Cont...)
[Link] Code:
<init-param>
<param-name>MyName</param-name>
<param-value>Chaitanya</param-value>
</init-param>
<init-param>
<param-name>MyWebsite</param-name>
<param-value>[Link]</param-value>
</init-param>

55
Example of ServletConfig Interface(Cont...)
[Link] Code:
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/scdemo</url-pattern>
</servlet-mapping>
</web-app>

56
Example of ServletConfig Interface(Cont...)
Output:

57
ServletContext Interface
❖ As we have already discussed about ServletConfig, the Servlet
Container creates ServletConfig object for each Servlet during
initialization.
❖ The main difference between ServletConfig and ServletContext is
that unlike ServletConfig, the ServletContext is being created once
per web application, i.e. ServletContext object is common to all the
servlets in web application.
58
Methods of ServletContext Interface
❖ public String getInitParameter(String param): It returns the
value of given parameter or null if the parameter doesn’t exist.
❖ public Enumeration getInitParameterNames(): Returns an
enumeration of context parameters names.
❖ public void setAttribute(String name,Object object): Sets the
attribute value for the given attribute name.

59
Methods of ServletContext Interface(Cont...)
❖ public Object getAttribute(String name):Returns the attribute
value for the given name or null if the attribute doesn’t exist.
❖ public String getServerInfo(): Returns the name and version of
the servlet container on which the servlet is running.
❖ public String getContextPath(): Returns the context path of the
web application.

60
ServletContext Object Creation
❖ This is how we can create ServletContext object. In this code we
are creating object in init() method, however you can create the
object anywhere you like.
ServletContext sc;
public void init(ServletConfig scfg)
{
sc=[Link]();
}

61
ServletContext Object Creation(Cont...)
❖ Once we have the ServletContext object, we can set the attributes
of the ServletContext object by using the setAttribute() method.
❖ Since the ServletContext object is available to all the servlets of the
Web application, other servlets can retrieve the attribute from the
ServletContext object by using the getAttribute() method.

62
ServletContext Object Creation(Cont...)
Context Initialization Parameter
❖ Context Initialization parameters are the parameter name and value pairs
that you can specify in the deployment descriptor file (the [Link] file).
❖ Here you can specify the parameters that will be accessible to all the
servlets in the web application.
❖ When we deploy the Web application, the Servlet container reads the
initialization parameter from the [Link] file and initializes the
ServletContext object with it.
63
ServletContext Object Creation(Cont...)
❖ We can use the getInitParameter() and getInitParameterNames()
methods of the ServletContext interface to get the parameter value
and enumeration of parameter names respectively.

64
Example of ServletContext Interface
❖ For a basic example, here I have specified the parameter email_id
with the value, since this is common to all the servlets, you can get
the parameter name and value in any servlet.

<context-param>
<param-name>email_id</param-name>
<param-value>beginnersbook@[Link]</param-value>
</context-param>

65
Example of ServletContext Interface(Cont...)
❖ In this comprehensive example, we have two context initialization
parameters (user name and user email) in [Link] file and we are
getting the value in Servlet using getInitParameter() method that
returns the value of given parameter.
- Example Servlet Code:
import [Link].*;
import [Link].*;
import [Link].*;

66
Example of ServletContext Interface(Cont...)
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
[Link]("text/html");
PrintWriter pwriter=[Link]();

//ServletContext object creation


ServletContext scontext=getServletContext();

67
Example of ServletContext Interface(Cont...)
//fetching values of initialization parameters and printing it
String userName=[Link]("uname");
[Link]("User name is="+userName);
String userEmail=[Link]("email");
[Link]("Email Id is="+userEmail);
[Link]();
}
}

68
Example of ServletContext Interface(Cont...)
- [Link] Code:
<web-app>
<servlet>
<servlet-name>BeginnersBook</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<context-param>
<param-name>uname</param-name>
<param-value>ChaitanyaSingh</param-value>
</context-param>

69
Example of ServletContext Interface(Cont...)
<context-param>
<param-name>email</param-name>
<param-value>beginnersbook@[Link]</param-value>
</context-param>
<servlet-mapping>
<servlet-name>BeginnersBook</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>

70
Example of ServletContext Interface(Cont...)
- Output:

71
Attribute in Servlet

72
What is Attribute 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 information 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.
73
Attribute specific methods
❖ There are following 4 attribute specific methods:
- public void setAttribute(String name,Object object): sets the given object
in the application scope.
- public Object getAttribute(String name): Returns the attribute for the
specified name.
- public Enumeration getInitParameterNames(): Returns the names of the
context initialization parameters as an Enumeration of String objects.
- public void removeAttribute(String name): Removes the attribute with
the given name from the servlet context.
74
Examples of Attribute in Servlet
❖ In this example, we are setting the attribute in the application scope and
getting that value from another servlet.
- Example 1([Link] - 2 Slides)
import [Link].*;
import [Link].*;
import [Link].*;
public class DemoServlet1 extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
75
Examples of Attribute in Servlet
try{
[Link]("text/html");
PrintWriter out=[Link]();
ServletContext context=getServletContext();
[Link]("company","IBM");
[Link]("Welcome to first servlet");
[Link]("<a href='servlet2'>visit</a>");
[Link]();
}catch(Exception e){[Link](e);}
}}
76
Examples of Attribute in Servlet
❖ In this example, we are setting the attribute in the application scope and
getting that value from another servlet.
- Example 2([Link] - 2 Slides)
import [Link].*;
import [Link].*;
import [Link].*;
public class DemoServlet2 extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
77
Examples of Attribute in Servlet
try{
[Link]("text/html");
PrintWriter out=[Link]();
ServletContext context=getServletContext();
String n=(String)[Link]("company");
[Link]("Welcome to "+n);
[Link]();
}catch(Exception e){[Link](e);}
}}
78
Examples of Attribute in Servlet
- [Link] - 2 Slides
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>DemoServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping> 79
Examples of Attribute in Servlet
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>DemoServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
80
Request Dispatcher
Interface

81
What is RequestDispatcher Interface?
❖ 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.
❖ It is one of the ways of servlet collaboration.

82
Methods of RequestDispatcher Interface
❖ The RequestDispatcher interface provides two methods. They are:
❖ public void forward(ServletRequest request, ServletResponse
response) throws ServletException, [Link]: Forwards a
request from a servlet to another resource (servlet, JSP file, or HTML file)
on the server.
❖ public void include(ServletRequest request, ServletResponse
response) throws ServletException, [Link]: Includes the
content of a resource (servlet, JSP page, or HTML file) in the response.
83
Methods of RequestDispatcher Interface(Cont...)
❖ As you can see in the figure, response of second servlet is sent to the client.
Response of the first servlet is not displayed to the user.

Fig. 4: forward() method


84
Methods of RequestDispatcher Interface(Cont...)
❖ As you can see in the figure, response of second servlet is included in the
response of the first servlet that is being sent to the client.

Fig. 5: include() method


85
Object creation of RequestDispatcher Interface
❖ The getRequestDispatcher() method of ServletRequest interface
returns the object of RequestDispatcher. Syntax:
- Syntax:
public RequestDispatcher getRequestDispatcher(String resource);
- Example of using getRequestDispatcher method
RequestDispatcher rd=[Link]("servlet2");
//servlet2 is the url-pattern of the second servlet
[Link](request, response);//method may be include or forward
86
Example of RequestDispatcher Interface
❖ In this example, we are validating the password entered by the
user.
❖ If password is servlet, it will forward the request to the
WelcomeServlet, otherwise will show an error message: sorry
username or password error!.

87
Example of RequestDispatcher Interface(Cont...)
❖ In this example, we have created following files:
- [Link] file: for getting input from the user.
- [Link] file: a servlet class for processing the response. If
password is servet, it will forward the request to the welcome servlet.
- [Link] file: a servlet class for displaying the welcome
message.
- [Link] file: a deployment descriptor file that contains the
information about the servlet.
88
Example of RequestDispatcher Interface(Cont...)

Fig. 6: RequestDispatcher Example Files


89
Example of RequestDispatcher Interface(Cont...)
- [Link]
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>

90
Example of RequestDispatcher Interface(Cont...)
- [Link] - 3 slides
import [Link].*;
import [Link].*;
import [Link].*;

public class Login extends HttpServlet {


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

91
Example of RequestDispatcher Interface(Cont...)
[Link]("text/html");
PrintWriter out = [Link]();
String n=[Link]("userName");
String p=[Link]("userPass");
if([Link]("servlet"){
RequestDispatcher rd=[Link]("servlet2");
[Link](request, response);
}

92
Example of RequestDispatcher Interface(Cont...)
else{
[Link]("Sorry UserName or Password Error!");
RequestDispatcher rd=[Link]("/[Link]");
[Link](request, response);
}
}
}

93
Example of RequestDispatcher Interface(Cont...)
- [Link] - 2 slides
import [Link].*;
import [Link].*;
import [Link].*;

public class WelcomeServlet extends HttpServlet {


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

94
Example of RequestDispatcher Interface(Cont...)
[Link]("text/html");
PrintWriter out = [Link]();
String n=[Link]("userName");
[Link]("Welcome "+n);
}
}

95
Example of RequestDispatcher Interface(Cont...)
- [Link] - 3 slides
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
96
Example of RequestDispatcher Interface(Cont...)
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

97
Example of RequestDispatcher Interface(Cont...)
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>

98
Example of RequestDispatcher Interface(Cont...)

99
Example of RequestDispatcher Interface(Cont...)

100
The Filter API:
Filter, FilterChain,
Filter Config
101
What is Filter in Servlet?
❖ A filter is an object that is invoked at the preprocessing and
postprocessing of a request.
❖ It is mainly used to perform filtering tasks such as conversion,
logging, compression, encryption and decryption, input validation etc.
❖ The servlet filter is pluggable, i.e. its entry is defined in the [Link]
file, if we remove the entry of filter from the [Link] file, filter will be
removed automatically and we don't need to change the servlet.
❖ So, maintenance cost will be less.
102
Filter in Servlet - Diagram
Note: Unlike Servlet, One filter doesn't have dependency on another filter.

Fig. 7: Filter in Servlet


103
Usages of Filter
❖ Recording all incoming requests
❖ Logs the IP addresses of the computers from which the requests
originate
❖ Conversion
❖ Data compression
❖ Encryption and decryption
❖ Input validation, etc.
104
Advantages of Filter
❖ Filter is pluggable.
❖ One filter don't have dependency onto another resource.
❖ Less Maintenance

105
How Filters Work?
❖ When a request reaches the Web Container, it checks if any filter has
URL patterns that matches the requested URL.
❖ The Web Container locates the first filter with a matching URL pattern
and filter's code is executed.
❖ If another filter has a matching URL pattern, its code is then executed.
This continues until there are no filters with matching URL patterns
left.

106
How Filters Work?(Cont...)
❖ If no error occurs, the request passes to the target servlet. Hence we
know, that the request will be passed to the target servlet only when
all the related Filters are successfully executed.
❖ The servlet returns the response back to its caller. The last filter that
was applied to the request is the first filter applied to the response.
❖ At last the response will be passed to the Web Container which passes
it to the client.

107
Filter API
❖ Like servlet filter have its own API.
❖ The [Link] package contains the three interfaces of Filter
API.
- Filter
- FilterChain
- FilterConfig

108
Filter Interface
❖ For creating any filter, you must implement the Filter interface. Filter
interface provides the life cycle methods for a filter.

Method Description

public void init (FilterConfig init() method is invoked only once. It is used to initialize the filter.
config)

public void doFilter doFilter() method is invoked every time when user request to any
(HttpServletRequest request, resource, to which the filter is mapped. It is used to perform
HttpServletResponse filtering tasks.
response, FilterChain chain)

public void destroy() This is invoked only once when filter is taken out of the service.

109
FilterChain Interface
❖ The object of FilterChain is responsible to invoke the next filter or
resource in the chain.
❖ This object is passed in the doFilter method of Filter interface.
❖ The FilterChain interface contains only one method:
- public void doFilter (HttpServletRequest request,
HttpServletResponse response): it passes the control to the next
filter or resource.
110
How to define Filter?
❖ We can define filter same as servlet. Let's see the elements of filter
and filter-mapping.
<web-app>
<filter>
<filter-name>...</filter-name>
<filter-class>...</filter-class>
</filter>

111
How to define Filter?(Cont...)
<filter-mapping>
<filter-name>...</filter-name>
<url-pattern>...</url-pattern>
</filter-mapping>
</web-app>
❖ For mapping filter we can use, either url-pattern or servlet-name.
❖ The url-pattern elements has an advantage over servlet-name
element i.e. it can be applied on servlet, JSP or HTML.

112
Simple Example of Filter
❖ In this example, we are simply displaying information that filter is
invoked automatically after the post processing of the request.
- [Link]
<a href="servlet1">click here</a>
- [Link]
import [Link];
import [Link];
import [Link].*;

113
Simple Example of Filter(Cont...)
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=[Link]();
[Link]("filter is invoked before");
[Link](req, resp);//sends request to next resource
[Link]("filter is invoked after");
}
public void destroy() {}
}
114
Simple Example of Filter(Cont...)
- [Link]
import [Link];
import [Link];
import [Link];
import [Link].*;
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

115
Simple Example of Filter(Cont...)
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<br>welcome to servlet<br>");
}
}
[Link]

116
Simple Example of Filter(Cont...)
- [Link]
❖ For defining the filter, filter element of web-app must be defined just
like servlet.
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>

117
Simple Example of Filter(Cont...)
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<filter>
<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>
118
Cookies and Session
Management

119
Managing Sessions 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.
❖ E.g., 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.
120
Managing Sessions in Servlets(Cont...)
❖ 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:
- Cookies
- Hidden form field
- URL Rewriting
- HttpSession
121
How Session Works - Diagram

Fig. 8: How Session Works


122
How Session Works - Explanation
❖ Session is used to store everything that we can get from the client from all the
requests the client makes.
❖ The basic concept behind session is, 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 it is 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.
123
Servlet: What is 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.

124
Servlet: How HttpSession works

Fig. 9: How HttpSession Works

125
Servlet: How HttpSession works - Explanation
❖ 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.
❖ 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.
❖ The Web Container uses this ID, finds the matching session with the
ID and associates the session with the request.
126
Servlet: HttpSession Interface

Fig. 10: HttpSession Interface


127
URL Rewriting

128
URL Rewriting
❖ If your browser does not support cookies, URL rewriting provides you
with another session tracking alternative.
❖ In URL rewriting, we append a token or identifier to the URL of the
next Servlet or the next resource.
❖ We can send parameter name/value pairs using the following format:
- url?name1=value1&name2=value2&??

129
URL Rewriting(Cont…)

Fig. 11: URL Rewriting

130
Advantages and Disadvantages
Advantage of URL Rewriting
❖ It will always work whether cookie is disabled or not (browser
independent).
❖ Extra form submission is not required on each pages.
Disadvantage of URL Rewriting
❖ It will work only with links.
❖ It can send Only textual information.

131
End of the Topic

132

You might also like