Servlet Notes
Servlet Notes
Website
Website is a collection of related web pages that may contain text, images, audio
and video. The first page of a website is called home page. Each website has
specific internet address (URL) that you need to enter in your browser to access
a website.
Website is hosted on one or more servers and can be accessed by visiting its
homepage using a computer network. A website is managed by its owner that
can be an individual, company or an organization.
A website can be of two types:
o Static Website
o Dynamic Website
Static website
Static website is the basic type of website that is easy to create. You don't need
the knowledge of web programming and database design to create a static
website. Its web pages are coded in HTML.
Advertisement
The codes are fixed for each page so the information contained in the page does
not change and it looks like a printed page.
Dynamic website
Dynamic website is a collection of dynamic web pages whose content changes
dynamically. It accesses content from a database or Content Management
System (CMS). Therefore, when you alter or update the content of the database,
the content of the website is also altered or updated.
Dynamic website uses client-side scripting or server-side scripting, or both to
generate dynamic content.
Client side scripting generates content at the client computer on the basis of user
input. The web browser downloads the web page from the server and processes
the code within the page to render information to the user.
In server side scripting, the software runs on the server and processing is
completed in the server then plain pages are sent to the user.
Servlet
Servlet technology is used to create a web application (resides at server side
and generates a dynamic web page).
Servlet technology is robust and scalable because of java language. Before
Servlet, CGI (Common Gateway Interface) scripting language was common as
a server-side programming language. However, there were many disadvantages
to this technology. We have discussed these disadvantages below.
There are many interfaces and classes in the Servlet API such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.
What is a Servlet?
Servlet can be described in many ways, depending on the context.
o Servlet is a technology which is used to create a web application.
o Servlet is an API that provides many interfaces and classes including
documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds
to the incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a
dynamic web page.
Advantages of Servlet
There are many advantages of Servlet over CGI. The web container creates
threads for handling the multiple requests to the Servlet. Threads have many
benefits over the Processes such as they share a common memory area,
lightweight, cost of communication between the threads are low. The
advantages of Servlet are as follows:
1. Better performance: because it creates a thread for each request, not
process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the
memory leak, garbage collection, etc.
4. Secure: because it uses java language.
Life Cycle of a Servlet (Servlet Life Cycle)
The web container maintains the life cycle of a servlet instance.
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
As displayed in the above diagram, there are three states of a servlet: new, ready
and end. The servlet is in new state if servlet instance is created. After invoking
the init() method, Servlet comes in the ready state. In the ready state, servlet
performs all the tasks. When the web container invokes the destroy() method, it
shifts to the end state.
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
There are many interfaces in javax.servlet package. They are as follows:
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
Classes in javax.servlet package
There are many classes in javax.servlet package. They are as follows:
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletContextEvent
5. ServletContextAttributeEvent
Servlet Interface
Servlet interface provides common behavior to all the servlets. Servlet
interface defines methods that all servlets must implement.
Servlet interface needs to be implemented for creating any servlet (either
directly or indirectly). It provides 3 life cycle methods that are used to initialize
the servlet, to service the requests, and to destroy the servlet and 2 non-life
cycle methods.
Methods of Servlet interface
There are 5 methods in Servlet interface. The init, service and destroy are the
life cycle methods of servlet. These are invoked by the web container.
Method Description
public ServletConfig
returns the object of ServletConfig.
getServletConfig()
import java.io.*;
import javax.servlet.*;
public class First implements Servlet{
ServletConfig config=null;
ServletConfig Interface
An object of ServletConfig is created by the web container for each servlet. This
object can be used to get configuration information from web.xml file.
If the configuration information is modified from the web.xml file, we don't
need to change the servlet. So it is easier to manage the web application if any
specific content is modified from time to time.
Advantage of ServletConfig
The core advantage of ServletConfig is that you don't need to edit the servlet
file if information is modified from the web.xml file.
Methods of ServletConfig interface
1. public String getInitParameter(String name):Returns the parameter
value for the specified parameter name.
2. public Enumeration getInitParameterNames():Returns an enumeration
of all the initialization parameter names.
3. public String getServletName():Returns the name of the servlet.
4. public ServletContext getServletContext():Returns an object of
ServletContext.
ServletContext Interface
An object of ServletContext is created by the web container at time of
deploying the project. This object can be used to get configuration information
from web.xml file. There is only one ServletContext object per web application.
If any information is shared to many servlet, it is better to provide it from the
web.xml file using the <context-param> element.
Advantage of ServletContext
Easy to maintain if any information is shared to all the servlet, it is better to
make it available for all the servlet. We provide this information from the
web.xml file, so if the information is changed, we don't need to modify the
servlet. Thus it removes maintenance problem.
Usage of ServletContext Interface
There can be a lot of usage of ServletContext object. Some of them are as
follows:
1. The object of ServletContext provides an interface between the container
and servlet.
2. The ServletContext object can be used to get configuration information
from the web.xml file.
3. The ServletContext object can be used to set, get or remove attribute from
the web.xml file.
4. The ServletContext object can be used to provide inter-application
communication.
There is given some commonly used methods of ServletContext interface.
1. public String getInitParameter(String name):Returns the parameter
value for the specified parameter name.
2. public Enumeration getInitParameterNames():Returns the names of
the context's initialization parameters.
3. public void setAttribute(String name,Object object):sets the given
object in the application scope.
4. public Object getAttribute(String name):Returns the attribute for the
specified name.
5. public Enumeration getInitParameterNames():Returns the names of
the context's initialization parameters as an Enumeration of String
objects.
6. public void removeAttribute(String name):Removes the attribute with
the given name from the servlet context.
ServletRequest Interface
An object of ServletRequest is used to provide the client request
information to a servlet such as content type, content length, parameter names
and values, header informations, attributes etc.
Methods of ServletRequest interface
Method Description
ServletResponse Interface
• ServletOutputStream getOutputStream() throws IOException -Used to
write binary data to the response
• Void getContentType() – Returns the content type for the response .
• PrintWriter getWriter() throws IOException - Used to write a character
data to the response
RequestDispatcher in Servlet
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.
Methods of RequestDispatcher interface
The RequestDispatcher interface provides two methods. They are:
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.
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.
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.
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. Syntax:
Syntax of getRequestDispatcher method
public RequestDispatcher getRequestDispatcher(String resource);
Example of using getRequestDispatcher method
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
//servlet2 is the url-pattern of the second servlet