Understanding Java Servlets Basics
Understanding Java Servlets Basics
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?
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.
20
Servlet Life Cycle - Architecture
❖ 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.
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
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]
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 −
38
Basic Servlet Structure(Cont...)
import [Link].*;
import [Link].*;
import [Link].*;
42
Servlet - Deployment Descriptor(Cont...)
❖ 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.
<servlet>
<servlet-name>alias name</servlet-name>
</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]();
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.
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...)
90
Example of RequestDispatcher Interface(Cont...)
- [Link] - 3 slides
import [Link].*;
import [Link].*;
import [Link].*;
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].*;
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.
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
124
Servlet: 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
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…)
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