0% found this document useful (0 votes)
10 views10 pages

Java Servlets

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 10

Introduction to Java Servlets

Servlets are the Java programs that run on the Java-enabled web server or
application server. They are used to handle the request obtained from the
webserver, process the request, produce the response, then send a response back
to the webserver. In Java, to create web applications we use Servlets. To create
Java Servlets, we need to use Servlet API which contains all the necessary
interfaces and classes.

Servlet API has 2 packages namely:

• javax.servlet.http

• javax.servlet

Properties of Servlets are as follows:

• Servlets work on the server-side.

• Servlets are capable of handling complex requests obtained


from the webserver.

Servlets Architecture

Servlets are grouped under the Advanced Java tree that is used to
create dynamic web applications. Servlets are robust, well scalable, and
are primarily used in developing server-side applications. If we go a
little back in time, we would be able to witness that before the
introduction of servlets, CGI (Common Gateway Interface) was
used. Among several indigenous tasks that a servlet is capable of
doing, dynamically performing client requests and responses
are most common.
Advantages of a Java Servlet

 Servlet is faster than CGI as it doesn’t involve the creation of a new process for
every new request received.
 Servlets, as written in Java, are platform-independent.
 Removes the overhead of creating a new process for each request as Servlet
doesn’t run in a separate process. There is only a single instance that handles all
requests concurrently. This also saves the memory and allows a Servlet to easily
manage the client state.
 It is a server-side component, so Servlet inherits the security provided by the Web
server.
 The API designed for Java Servlet automatically acquires the advantages of the
Java platforms such as platform-independent and portability. In addition, it
obviously can use the wide range of APIs created on Java platforms such as
JDBC to access the database.
 Many Web servers that are suitable for personal use or low-traffic websites are
offered for free or at extremely cheap costs eg. Java servlet. However, the
majority of commercial-grade Web servers are rather expensive, with the notable
exception of Apache, which is free.

The Servlet Container


Servlet container, also known as Servlet engine is an integrated set of objects that
provide a run time environment for Java Servlet components. In simple words, it is a
system that manages Java Servlet components on top of the Web server to handle the
Web client requests.

Services provided by the Servlet container :


 Network Services: Loads a Servlet class. The loading may be from a local file
system, a remote file system or other network services. The Servlet container
provides the network services over which the request and response are sent.
 Decode and Encode MIME-based messages: Provides the service of decoding
and encoding MIME-based messages.
 Manage Servlet container: Manages the lifecycle of a Servlet.
 Resource management Manages the static and dynamic resources, such as
HTML files, Servlets, and JSP pages.
 Security Service: Handles authorization and authentication of resource access.
 Session Management: Maintains a session by appending a session ID to the URL
path.
Interfaces in javax.servlet package

1. Filter: To perform filtering tasks on either the request to a resource, or on the


response from a resource, or both.

2. FilterChain: To provide a view into the invocation chain of a filtered request


for a resource to the developer by the servlet container.

3. FilterConfig :To pass information to a filter during initialization used by a


servlet container.

4. RequestDispatcher:It defines an object to dispatch the request and response to


any other resource, means it receives requests from the client and sends them to
a servlet/HTML file/JSP file on the server.

5. Servlet : This is the main interface that defines the methods in which all the
servlets must implement. To implement this interface, write a generic servlet
that extends javax.servlet.GenericServlet or an HTTP servlet that extends
javax.servlet.http.HttpServlet.

6. ServletConfig : It defines an object created by a servlet container at the time of


servlet instantiation and to pass information to the servlet during initialization.

7. ServletContex : tIt defines a set of methods that a servlet uses to communicate


with its servlet container. The information related to the web application
available in web.xml file is stored in ServletContext object created by container.

8. ServletContextAttributeListener : The classes that implement this interface


receive notifications of changes to the attribute list on the servlet context of a
web application

9. ServletContextListener : The classes that implement this interface receive


notifications about changes to the servlet context of the web application they
are part of

10. ServletResponse : It defines an object created by servlet container to assist a


servlet in sending a response to the client.

11. ServletRequestAttributeListener : To generate the notifications of request


attribute changes while the request is within the scope of the web application in
which the listener is registered.
Exceptions in javax.servlet package:

Exception Name Description

A general exception thrown by a servlet when it encounters


ServletException
difficulty.

Thrown by a servlet or filter to indicate that it is permanently


UnavailableException
or temporarily unavailable.

javax.servlet.http

 This package provides the number of interfaces and classes to support HTTP
servlet which is HTTP protocol dependent.

 These interfaces and classes describe and define the contracts between a servlet
class running under HTTP protocol and the runtime environment provided by a
servlet container.

Classes available in javax.servlet.http package:

Class Name Description

Creates a cookie object. It is a small amount of


information sent by a servlet to a Web browser,
Cookie
saved by the browser, and later sent back to the
server used for session management.

Provides an abstract class that defines methods to


HttpServlet create an HTTP suitable servlet for a web
application.

This class provides implementation of the


HttpServletRequestWrapper HttpServletRequest interface that can be subclassed
to adapt the request to a Servlet.

This class provides implementation of the


HttpServletResponseWrapper HttpServletResponse interface that can be subclassed
to adapt the response from a Servlet.
Interfaces available in javax.servlet.http package:

Interface Name Description

To provide client HTTP request information for


HttpServletRequest
servlets. It extends the ServletRequest interface.

To provide HTTP-specific functionality in sending


HttpServletResponse a response to client. It extends
the ServletResponse interface.

It provides a way to identify a user across web


HttpSession application/web site pages and to store information
about that user.

Container to notify all the objects that are bound to


HttpSessionActivationListener a session that sessions will be passivated and that
session will be activated.

To get notifications of changes to the attribute lists


HttpSessionAttributeListener of sessions within this web application, this listener
interface can be implemented.

It causes an object to be notified by an


HttpSessionBindingListener HttpSessionBindingEvent object, when it is bound
to or unbound from a session.

To receive notification events related to the changes


HttpSessionListener
to the list of active sessions in a web application.
GenericServlet Class

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.

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.
Servlet Example by inheriting the GenericServlet class

import java.io.*;
import javax.servlet.*;

public class First extends GenericServlet{


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 generic servlet</b>");
out.print("</body></html>");

}
}

HttpServlet Class

The HttpServlet class extends the GenericServlet class and implements Serializable
interface. It provides http specific methods such as doGet, doPost, doHead, doTrace
etc.

Methods of HttpServlet class

There are many methods in HttpServlet class. They are as follows:

1. public void service(ServletRequest req,ServletResponse res) dispatches the


request to the protected service method by converting the request and response
object into http type.
2. protected void service(HttpServletRequest req, HttpServletResponse
res) receives the request from the service method, and dispatches the request to
the doXXX() method depending on the incoming http request type.
3. protected void doGet(HttpServletRequest req, HttpServletResponse
res) handles the GET request. It is invoked by the web container.
4. protected void doPost(HttpServletRequest req, HttpServletResponse
res) handles the POST request. It is invoked by the web container.
5. protected void doHead(HttpServletRequest req, HttpServletResponse
res) handles the HEAD request. It is invoked by the web container.
6. protected void doOptions(HttpServletRequest req, HttpServletResponse
res) handles the OPTIONS request. It is invoked by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse
res) handles the PUT request. It is invoked by the web container.
8. protected void doTrace(HttpServletRequest req, HttpServletResponse
res) handles the TRACE request. It is invoked by the web container.
9. Protected void doDelete(HttpServletRequest req,
HttpServletResponseres) handles the DELETE request. It is invoked by the web
container.
10. protected long getLastModified(HttpServletRequest req) returns the time
when HttpServletRequest was last modified since midnight January 1, 1970 GMT.

Example of HttpServlet class.

package com.gfg;

import javax.servlet.*;

import javax.servlet.http.*;

public class GFGServlet extends HttpServlet {

public void doGet(HttpServletRequest rq,

HttpServletResponse rs)

// here user write code to handle doGet request

// we are defining the doPost method of HttpServlet

// abstract class

public void doPost(HttpServletRequest rq,

HttpServletResponse rs)

// here user write code to handle doPost request

} // class ends
Life Cycle of a Servlet

The web container maintains the life cycle of a servlet instance. Let's see the life cycle
of the servlet:

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:

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:

. public void service(ServletRequest request, ServletResponse response)


. 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:

. public void destroy()

You might also like