Servlets 1
Servlets 1
destroy()
Servlet –Life Cycle Methods
destroy()
The destroy() method is called only once.
It is called at the end of the life cycle of the servlet.
This method performs various tasks such as closing connection with the database, releasing memory
allocated to the servlet, releasing resources that are allocated to the servlet and other cleanup
activities.
When this method is called, the garbage collector comes into action.
The prototype for this method is
public void destroy() { // Finalization code...}
How Servlets work?
1. When the web server (e.g. Apache Tomcat) starts up, the servlet container deploy and
loads all the servlets. During this step Servlet container creates ServletContext
object. ServletContext is an interface that defines the set of methods that a servlet can
use to communicate with the servlet container.
2. Once the servlet is loaded, the servlet container creates the instance of servlet class. For
each instantiated servlet, its init() method is invoked.
3. Client (user browser) sends an Http request to web server on a certain port. Each time
the web server receives a request, the servlet container creates HttpServletRequest and
HttpServletResponse objects. The HttpServletRequest object provides the access to the
request information and the HttpServletResponse object allows us to format and change
the http response before sending it to the client.
4. The servlet container spawns a new thread that calls service() method for each client
request. The service() method dispatches the request to the correct handler
method based on the type of request.
For example if server receives a Get Request the service() method would dispatch the
request to the doGet() method by calling the doGet() method with request parameters.
Similarly the requests like Post, Head, Put etc. are dispatched to the corresponding
handlers doPost(), doHead(), doPut() etc. by service() method of servlet.
How Servlets work?
5. When servlet container shuts down, it unloads all the servlets and calls
destroy() method for each initialized servlets.
How web container handles the
Servlet request
The web container is responsible for handling the client request
1. maps the request with the servlet in the web.xml file.
2. creates request and response objects for this request
3. calls the service method on the thread
4. The public service method internally calls the protected service method
5. The protected service method calls the doGet method depending on the type
of request
6. The doGet method generates the response and it is passed to the client.
7. After sending the response, the web container deletes the request and
response objects. The thread is contained in the thread pool or deleted
depends on the server implementation.
Client-Server Model setup
Pre-requisites
JDK
Maven -- > https://www.geeksforgeeks.org/how-to-install-apache-maven-on-windows/
Tomcat 9 See next slide
Vscode and Extensions for maven and Tomcat servers follow instructions in class
Tomcat Installation Guide
Follow the steps mentioned here :
Using zip
https://www.geeksforgeeks.org/how-to-install-apache-tomcat-on-windows/
Using installer
https://www.liquidweb.com/blog/installing-tomcat-9-on-windows/
Introduction to Servlet API
The javax.servlet and javax.servlet.http packages represent
interfaces and classes for servlet api.
The javax.servlet package contains many interfaces and classes that
are used by the servlet or web container. These are not specific to any
protocol.
The javax.servlet.http package contains interfaces and classes that
are responsible for http requests only.
Interfaces in javax.servlet package
GenericServlet class
implements Servlet, ServletConfig and Serializable interfaces.
It provides the implementation of all the methods of these interfaces except
the service method.
GenericServlet class can handle any type of request so it is protocol-
independent.
You may create a generic servlet by inheriting the GenericServlet class and
providing the implementation of the service method.
GenericServlet : Methods
Defines an object to provide client request Defines an object to provide client request
information to a servlet information to a servlet
The servlet container creates The servlet container creates
a ServletRequest object and passes it as an an HttpServletRequest object and passes it as an
argument to the servlet's service method. argument to the servlet's service methods
(doGet, doPost, etc).
A ServletRequest object provides data including A HttpServletRequest object also provides data
parameter name and values, attributes, and an including parameter name and values, attributes,
input stream and an input stream
Interfaces that extend ServletRequest can provide Extends the ServletRequest interface to provide
additional protocol-specific data request information for HTTP servlets
No session management api’s defined Session management api are defined in this class
like cookie , HttpSession
Difference between ServletResponse vs
HttpServletResponse
ServletResponse HttpServletResponse
This is an Interface This is also an Interface but extends
ServletResponse
Defines an object to assist a servlet in sending a Extends the ServletResponse interface to provide
response to the client. HTTP-specific functionality in sending a response.
For example, it has methods to access HTTP
headers and cookies.
The servlet container creates The servlet container creates
a ServletResponse object and passes it as an an HttpServletResponse object and passes it as an
argument to the servlet's service method argument to the servlet's service methods
(doGet, doPost, etc)
Difference between ServletConfig vs ServletContext
ServletConfig ServletContext
This is an Interface interface
A servlet configuration object used by a servlet Defines a set of methods that a servlet uses to
container to pass information to a servlet during communicate with its servlet container, for
initialization example, to get the MIME type of a file, dispatch
requests, or write to a log file.
ServletConfig is servlet specific There is one context per "web application" per
Java Virtual Machine
The ServletConfig object is contained within the The ServletContext object is contained within
ServletRequest object which the Web server the ServletConfig object, which the Web server
provides the servlet when the client request is provides the servlet when the servlet is initialized
recieved
Parameters of servletConfig are present as name- Parameters of servletContext are present as name-
value pair in <init-param> inside <servlet>. value pair in <context-param> which is outside of
<servlet> and inside <web-app>
ServletConfig object is obtained by ServletContext object is obtained by
getServletConfig() method getServletContext() method.
Use ServletConfig when only one servlet needs Use ServletContext when whole application needs
information shared by it. information shared by it
LAB Assignment 2
1. Create student signup page and Servlet, where student registers using
username ,password , First name , lastname , emailId and USN and saves
data in the database
2. Create a login page and servlet where the user login using username and
password and servlet will validate the input data and retrieves the user
information saved in step 1 and sends back as a response
Note :
3. Create 1 tables User(USN, FN ,LN, emailId, password)
4. Use MySql DB
5. Referencce -> https://www.geeksforgeeks.org/servlet-form-data/
RequestDispatcher
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.
It is one of the way of servlet collaboration.
There are two methods defined in the RequestDispatcher interface.
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.
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.
RequestDispatcher - forward
As you see in the above figure, response of second servlet is sent to the client.
Response of the first servlet is not displayed to the user.
RequestDispatcher - include
As you can see in the above figure, response of second servlet is included in the response
of the first servlet that is being sent to the client.
How to get the object of
RequestDispatcher
The getRequestDispatcher() method of ServletRequest interface returns the object
of RequestDispatcher
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
servlet2 is the url-pattern of the second servlet
rd.forward(request, response);
rd.include(request, response);
Example of RequestDispatcher interface
https://www.javatpoint.com/requestdispatcher-in-servlet
sendRedirect
The sendRedirect() method of HttpServletResponse interface can be used to
redirect response to another resource, it may be servlet, jsp or html file.
It accepts relative as well as absolute URL
It works at client side because it uses the url bar of the browser to make another
request. So, it can work inside and outside the server.
Example of sendRedirect() method
response.sendRedirect("https://kletech.ac.in ");
Difference between forward() and
sendRedirect() method
https://www.javatpoint.com/sendRedirect()-method