0% found this document useful (0 votes)
14 views

Servlet Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Servlet Notes

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Servlets

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.

Static Website Dynamic Website

Prebuilt content is same every time Content is generated quickly and


the page is loaded. changes regularly.

It uses the server side languages such


It uses the HTML code for as PHP,SERVLET, JSP, and
developing a website. ASP.NET etc. for developing a
website.
It sends exactly the same response for It may generate different HTML for
every request. each of the request.

The page contains "server-side" code


The content is only changed when
which allows the server to generate
someone publishes and updates the
the unique content when the page is
file (sends it to the web server).
loaded.

Content Management System (CMS)


Flexibility is the main advantage of
is the main advantage of dynamic
static website.
website.

Static vs Dynamic website

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.

What is a web application?


A web application is an application accessible from the web. A web application
is composed of web components like Servlet, JSP, Filter, etc. and other elements
such as HTML, CSS, and JavaScript. The web components typically execute in
Web Server and respond to the HTTP request.

CGI (Common Gateway Interface)


CGI technology enables the web server to call an external program and pass
HTTP request information to the external program to process the request. For
each request, it starts a new process.
Disadvantages of CGI
There are many problems in CGI technology:
1. If the number of clients increases, it takes more time for sending the
response.
2. For each request, it starts a process, and the web server is limited to start
processes.
3. It uses platform dependent language e.g. C, C++, perl.

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.

1) Servlet class is loaded


The classloader is responsible to load the servlet class. The servlet class is
loaded when the first request for the servlet is received by the web container.

2) Servlet instance is created


The web container creates the instance of a servlet after loading the servlet
class. The servlet instance is created only once in the servlet life cycle.

3) init method is invoked


The web container calls the init method only once after creating the servlet
instance. The init method is used to initialize the servlet. It is the life cycle
method of the javax.servlet.Servlet interface. Syntax of the init method is given
below:
1. public void init(ServletConfig config) throws ServletException

4) service method is invoked


The web container calls the service method each time when request for the
servlet is received. If servlet is not initialized, it follows the first three steps as
described above then calls the service method. If servlet is initialized, it calls the
service method. Notice that servlet is initialized only once. The syntax of the
service method of the Servlet interface is given below:
1. public void service(ServletRequest request, ServletResponse response)
2. throws ServletException, IOException

5) destroy method is invoked


The web container calls the destroy method before removing the servlet
instance from the service. It gives the servlet an opportunity to clean up any
resource for example memory, thread etc. The syntax of the destroy method of
the Servlet interface is given below:
1. public void destroy()
Types of Servlet
How to Create Servlet According to servlet API we have three ways to creating
a servlet class.
• By implementing servlet interface
• By extending GenericServlet class
• By extending HttpServlet class

• By implementing servlet interface Example


public class myServlet implements Servlet ....... ....... }

• By extending GenericServlet class Example


public class myServlet extends GenericServlet ....... ....... }

• By extending HttpServlet class Example


public class myServlet extends HttpServlet ....... ....... }

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

Interfaces in javax.servlet.http package


There are many interfaces in javax.servlet.http package. They are as follows:
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:
1. HttpServlet
2. Cookie
3. HttpSessionEvent
4. HttpSessionBindingEvent

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

initializes the servlet. It is the life


public void init(ServletConfig
cycle method of servlet and invoked
config)
by the web container only once.

provides response for the incoming


public void service(ServletRequest
request. It is invoked at each request
request,ServletResponse response)
by the web container.

is invoked only once and indicates


public void destroy()
that servlet is being destroyed.

public ServletConfig
returns the object of ServletConfig.
getServletConfig()

returns information about servlet


public String getServletInfo() such as writer, copyright, version
etc.

Servlet Example by implementing Servlet interface


File: First.java

import java.io.*;
import javax.servlet.*;
public class First implements Servlet{
ServletConfig config=null;

public void init(ServletConfig config){


this.config=config;
System.out.println("servlet is initialized");
}
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");
}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}
}

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

public String is used to obtain the value of


getParameter(String name) a parameter by name.

returns an array of String


public String[] containing all values of given
getParameterValues(String parameter name. It is mainly
name) used to obtain values of a
Multi select list box.

returns an enumeration of all


java.util.Enumeration
of the request parameter
getParameterNames()
names.

Returns the size of the


public int
request entity data, or -1 if
getContentLength()
not known.

Returns the character set


public String
encoding for the input of this
getCharacterEncoding()
request.

Returns the Internet Media


public String
Type of the request entity
getContentType()
data, or null if not known.

public ServletInputStream Returns an input stream for


getInputStream() throws reading binary data in the
IOException request body.
Returns the host name of the
public abstract String
server that received the
getServerName()
request.

Returns the port number on


public int getServerPort() which this request was
received.

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

rd.forward(request, response);//method may be include or forward

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!. In
this program, we are cheking for hardcoded information. But you can check
it to the database also that we will see in the development chapter. In this
example, we have created following files:
• index.html file: for getting input from the user.
• Login.java file: a servlet class for processing the response. If password is
servet, it will forward the request to the welcome servlet.
• WelcomeServlet.java file: a servlet class for displaying the welcome
message.
• web.xml file: a deployment descriptor file that contains the information
about the servlet.
GenericServlet class
Generic servlet 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.
Methods of GenericServlet class
There are many methods in GenericServlet class. They are as follows:
1. public void init(ServletConfig config) is used to initialize the servlet.
2. public abstract void service(ServletRequest request, ServletResponse
response) provides service for the incoming request. It is invoked at each
time when user requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and
indicates that servlet is being destroyed.
4. public ServletConfig getServletConfig() returns the object of
ServletConfig.
5. public String getServletInfo() returns information about servlet such as
writer, copyright, version etc.
6. public void init() it is a convenient method for the servlet programmers,
now there is no need to call super.init(config)
7. public ServletContext getServletContext() returns the object of
ServletContext.
8. public String getInitParameter(String name) returns the parameter
value for the given parameter name.
9. public Enumeration getInitParameterNames() returns all the
parameters defined in the web.xml file.
10.public String getServletName() returns the name of the servlet object.
11.public void log(String msg) writes the given message in the servlet log
file.
12.public void log(String msg,Throwable t) writes the explanatory
message in the servlet log file and a stack trace.

You might also like