1.JAVA MODULE6 Servlet
1.JAVA MODULE6 Servlet
1.JAVA MODULE6 Servlet
MODULE-6
SERVLET
Module - 6
Servlets (7 hours)
Introduction to servlet
3 11/2/2022 3:55:13 PM
Introduction
Servlet Technology is used to create web applications.
Servlet technology uses Java language to create web
applications.
Web applications are helper applications that resides
at web server and build dynamic web pages.
A dynamic page could be anything like a page that
randomly chooses picture to display or even a page
that displays the current time.
Web applications made using Servlet are Secured,
Scalable and Robust.
Servlet
Working of Web Server
Advantages of using Servlets
1. Less response time because each request runs in a
separate thread.
2. Servlets are scalable.
3. Servlets are robust and object oriented.
4. Servlets are platform independent.
Servlet API
Servlet API consists of two important packages that
encapsulates all the important classes and interfaces,
namely :
1. javax.servlet
2. javax.servlet.http
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
Files and Resources
Classes and Interface of javax.servlet.http
CLASSES INTERFACES
HttpServlet HttpServletRequest
HttpServletResponse HttpSessionAttributeListener
HttpSession HttpSessionListener
Cookie HttpSessionEvent
Servlet Interface
Servlet Interface provides five methods.
Out of these five methods, three methods are Servlet life
cycle methods and rest two are non life cycle methods.
GenericServlet Class
GenericServlet is an abstract class that provides implementation of most of the basic
servlet methods. This is a very important class.
Methods of GenericServlet class
1. public void init(ServletConfig)
2. public abstract void service(ServletRequest request,ServletResposne response)
3. public void destroy()
4. public ServletConfig getServletConfig()
5. public String getServletInfo()
6. public ServletContext getServletContext()
7. public String getInitParameter(String name)
8. public Enumeration getInitParameterNames()
9. public String getServletName()
10. public void log(String msg)
11. public void log(String msg, Throwable t)
HttpServlet class
HttpServlet is also an abstract class.
This class gives implementation of various service() methods
of Servlet interface.
To create a servlet, we should create a class that extends
HttpServlet abstract class.
The Servlet class that we will create, must not override
service() method. Our servlet class will override only the
doGet() and/or doPost() methods.
The service() method of HttpServlet class listens to the Http
methods (GET, POST etc) from request stream and invokes
doGet() or doPost() methods based on Http Method type.
Servlet session is maintained in servlet context and it is being
provided by HTTP
How a Servlet Application works
Web container is responsible for managing execution of
servlets and JSP pages for Java EE application.
When a request comes in for a servlet, the server hands the
request to the Web Container.
Web Container is responsible for instantiating the servlet
or creating a new thread to handle the request.
Its the job of Web Container to get the request and response
to the servlet.
The container creates multiple threads to process multiple
requests to a single servlet.
Servlets don't have a main() method. Web Container
manages the life cycle of a Servlet instance.
Step -1
User sends request for a servlet by clicking a link that has
URL to a servlet.
Step-2
The container finds the servlet using deployment
descriptor and creates two objects :
HttpServletRequest
HttpServletResponse
Step-3
Then the container creates or allocates a thread for that
request and calls the Servlet's service() method and passes
the request, response objects as arguments.
Step-4
The service() method, then decides which servlet method,
doGet() or doPost() to call, based on HTTP Request
Method(Get, Post etc) sent by the client.
Step-5
Then the Servlet uses response object to write the
response back to the client.
Step-6
After the service() method is completed the thread dies.
And the request and response objects are ready for
garbage collection.
Servlet Life Cycle
Servlet Life Cycle
1. Loading Servlet Class : A Servlet class is loaded when first request for
the servlet is received by the Web Container.
2. Servlet instance creation :After the Servlet class is loaded, Web
Container creates the instance of it. Servlet instance is created only once
in the life cycle.
3. Call to the init() method : init() method is called by the Web Container
on servlet instance to initialize the servlet. Signature of init() method :
public void init(ServletConfig config) throws ServletException
4. Call to the service() method : The containers call the service() method
each time the request for servlet is received. The service() method will
then call the doGet() or doPost() method based on the type of the HTTP
request. Signature of service() method :
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
5. Call to destroy() method: The Web Container call the destroy()
method before removing servlet instance, giving it a chance for cleanup
activity.
Deployment Descriptor
In a java web application a file named web.xml is known
as deployment descriptor.
It is a xml file and <web-app> is the root element for it.
When a request comes web server uses web.xml file to
map the URL of the request to the specific code that
handle the requests
Sample web.xml file
<web-app>
<servlet>
<servlet-name>sampleservlet</servlet-name>
<servlet-class>sampleservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sampleservlet</servlet-name>
<url-pattern>/sampleservlet</url-pattern>
</servlet-mapping>
</web-app>
How web.xml works:
When a request comes it is matched with url pattern in
servlet mapping attribute.
You can specify a url pattern according to your need.
When url matched with url pattern, web server try to find
the servlet name in servlet attributes same as in servlet
mapping attribute.
When match found control goes to the associated servlet
class.
welcome-file-list in web.xml
<web-app> <web-app>
<welcome-file-list> <session-config>
<welcome-file>home.html</welcome-file> <session-timeout>
30
</welcome-file-list>
</session-timeout>
</web-app> </session-config>
</web-app>
Session Timeout:
</web-app>
Session timeout represents the event occuring when a user does not perform
any action on a web site during an interval (defined by a web server). The
event, on the server side, changes the status of the user session to 'invalid‘.
Session-conig: The number of minutes after which sessions in this Web
application expire.
RequestDispatcher interface
Index.html
Button
Example-1
Welcome.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class welcome extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
String name=req.getParameter("name");//will return value
pw.println("Welcome "+name);
pw.close();
}
}
Example-1
web.xml
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Example-2
Example-2
newhtml2.html
Example-2
login.java
Example-2 web.xml
welcome2.java <?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<web-app>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>login</servlet-class>
</servlet>
<servlet>
<servlet-name>welcome2</servlet-name>
<servlet-class>welcome2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>welcome2</servlet-name>
<url-pattern>/welcome2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>newhtml2.html</welcome-file>
</welcome-file-list>
</web-app>
Example-3
index.java
Example-3
insertservlet1.java
Example-3
retrieveservlet1.java
Example-3
web.xml
https://www.studytonight.com/servlet/creating-servlet-in-
netbeans.php
https://www.javatpoint.com/creating-servlet-in-netbeans-
ide
Session Tracking and Management in
Servlets
Session Tracking and Management
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an
user. It is also known as session management in servlet.
Http protocol is a stateless so we need to maintain state
using session tracking techniques.
Each time user requests to the server, server treats the
request as the new request. So we need to maintain the state
of an user to recognize to particular user.
HTTP is stateless that means each request is considered as
the new request.
Session Tracking and Management
Session Tracking and Management
Session Tracking Techniques
There are four techniques used in Session tracking:
Cookies
Hidden Form Field
URL Rewriting
HttpSession
Session Tracking and Management
Cookies in Servlet
A cookie is a small piece of information that is persisted
between the multiple client requests.
A cookie has a name, a single value, and optional attributes such
as a comment, path and domain qualifiers, a maximum age, and
a version number.
How Cookie works
By default, each request is considered as a new request. In
cookies technique, we add cookie with response from the
servlet. So cookie is stored in the cache of the browser. After
that if request is sent by the user, cookie is added with request
by default. Thus, we recognize the user as the old user
Session Tracking and Management
Types of Cookie
• There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
• Non-persistent cookie
• It is valid for single session only. It is removed each time when user
closes the browser.
• Persistent cookie
• It is valid for multiple session . It is not removed each time when user
closes the browser. It is removed only if user logout or signout.
Session Tracking and Management
//Create cookie
Cookie ck=new Cookie("user",“UUU");//creating cookie object
response.addCookie(ck);//adding cookie in the response
//Delete Cookie
Cookie ck=new Cookie("user","");//deleting value of cookie
ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response
//Get Cookie
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of c
ookie
}
Session Tracking and Management
Hidden Form Field
In case of Hidden Form Field a hidden (invisible) textfield is used
for maintaining the state of an user.
In such case, we store the information in the hidden field and get it
from another servlet. This approach is better if we have to submit
form in all the pages and we don't want to depend on the browser.
<input type="hidden" name="uname" value=“UUU">
Here, uname is the hidden field name and Vimal is the hidden field
value.
It is widely used in comment form of a website. In such case, we
store page id or page name in the hidden field so that each page can
be uniquely identified
request.getParameter("uname");
Session Tracking and Management
URL Rewriting
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&??
A name and a value is separated using an equal = sign, a
parameter name/value pair is separated from another parameter
using the ampersand(&). When the user clicks the hyperlink,
the parameter name/value pairs will be passed to the server.
From a Servlet, we can use getParameter() method to obtain a
parameter value.
<a href='servlet2?uname="+n+"'>visit</a>
request.getParameter("uname");
Session Tracking and Management
Session Tracking and Management
HttpSession interface
Container creates a session id for each user.
The container uses this id to identify the particular user.
An object of HttpSession can be used to perform two
tasks:
bind objects
view and manipulate information about a session, such as the
session identifier, creation time, and last accessed time.
Session Tracking and Management
The HttpServletRequest interface provides two methods to get the object of
HttpSession:
public HttpSession getSession():Returns the current session associated with this
request, or if the request does not have a session, creates one.
public HttpSession getSession(boolean create):Returns the current HttpSession
associated with this request or, if there is no current session and create is true,
returns a new session.
HttpSession session=request.getSession();
HttpSession session=request.getSession(false);