0% found this document useful (0 votes)
7 views20 pages

Servlet API

Uploaded by

Navneet Sheoran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views20 pages

Servlet API

Uploaded by

Navneet Sheoran
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Servlet API

Servlet API consists of two important packages that encapsulates all the important
classes and interface, namely :

 [Link]
 [Link]
Some Important Classes and Interfaces of [Link]

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
Some Important Classes and Interface of [Link]

CLASSES and INTERFACES

HttpServlet HttpServletRequest

HttpServletResponse HttpSessionAttributeListener

HttpSession HttpSessionListener

Cookie HttpSessionEvent
Servlet Interface

In Java, An interface is used for the development of servlet. This interface is known as the servlet inter-
face. This interface is implemented by all the interfaces. The servlet interface is used for the declaration
of init(), service(), and destroy() method. These methods are called by the server during the life cycle of
a servlet. The getServletConfig() method is called by the servlet to initialize the parameters. And the
getServletInfo() method is used for providing important information.
Servlet Interface provides only five methods. Out of these five methods, three methods are of Servlet
life cycle methods and rest two are non-life cycle methods.
Declaration :

public interface Servlet


Methods of Servlet interface

[Link]. Method Description

It is used for initializing the


public void init servlet. It is invoked only once by
1.
(ServletConfigconfig) the web container in a servlet life
cycle.
It is used for providing a re-
public void service sponse to all the incoming re-
2. (ServletRequestreq, quest. It is invoked every time by
ServletResponse res) the web container for each re-
quest.
It is used for destroying the
3. public void destroy() servlet. It is invoked only once in
a life cycle of a servlet.

public ServletConfigget- It is used to get the object of


4.
ServletConfig() ServletConfig.

It is used to get information


5. Public String getServletInfo() about writer, copyright etc of a
servlet.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Navneet Sheoran => servlet interface example</title>
</head>
<body>
<h1>Navneet sheoran</h1><br><br>
************************************<br><br>
<h3><a href="demo">Click here to proceed...</a></h3><br><br>

************************************<br><br>
</body>
</html>
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns:xsi="[Link]
instance"xmlns="[Link]
[Link]/xml/ns/javaee [Link]
app_4_0.xsd"id="WebApp_ID"version="4.0">
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/demo</url-pattern>
</servlet-mapping>
</web-app>
import [Link].*;
import [Link].*;
public class DemoServlet implements Servlet{
ServletConfig config=null;
public void init(ServletConfig config){
[Link]=config;
}
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
[Link]("text/html");
PrintWriter pwriter=[Link]();
[Link]("<html>");
[Link]("<body>");
[Link]("<h1>Hello Welcome to Here. This example is of servlet interface. </h1>");
[Link]("</body>");
[Link]("</html>");
}
public void destroy(){
[Link]("servlet destroy");
}
public ServletConfig getServletConfig(){
return config;
}
public String getServletInfo(){
return "[Link]";
}
}
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.
Methods of HttpServlet interface
[Link]. Method Description
It is used for securing the service
public void service(ServletRequest
1 method by creating objects of re-
req,ServletResponse res)
quest and response.
protected void service
It is used for receiving a service
2 (HttpServletRequest req, HttpS-
method.
ervletResponse res)
protected void doGet It is invoked by the web container
3 (HttpServletRequest req, HttpS- and it is used for handling the GET
ervletResponse res) request.
protected void doPost
It is invoked by the web container
4 (HttpServletRequest req, HttpS-
and it handles the POST request.
ervletResponse res)
protected void doHead
It is invoked by the web container
5 (HttpServletRequest req, HttpS-
and it handles the HEAD request.
ervletResponse res)
protected void doOptions It is invoked by the web container
6 (HttpServletRequest req, HttpS- and it handles the OPTIONS re-
ervletResponse res) quest.
protected void doPut It is invoked by the web container
7 (HttpServletRequest req, HttpS- and it handles the OPTIONS re-
ervletResponse res) quest.
protected void doTrace
It is invoked by the web container
8 (HttpServletRequest req, HttpS-
and it handles the TRACE request
ervletResponse res)
protected void doDelete
It is invoked by the web container
9 (HttpServletRequest req, HttpS-
and it handles the DELETE request.
ervletResponse res)
protected long getLastModified It is used for getting the time of
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="mar" align="center">
<h3 align="center">Navneet Sheoran</h3>
<h3 align="center">--------------------------------------------------------</h3>
Enter marks of the following subjects<br><br><br>
Maths : <input type="text" name="num1"><br><br>
English : <input type="text" name="num2"><br><br>
Hindi : <input type="text" name="num3"><br><br>
Science : <input type="text" name="num4"><br><br>
Social Science : <input type="text" name="num5"><br><br>
IT : <input type="text" name="num6"><br><br>
<input type="submit">
</form>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="[Link] xmlns="http://
[Link]/xml/ns/javaee" xsi:schemaLocation="[Link] http://
[Link]/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
< <servlet>
<servlet-name>abc2</servlet-name>
<servlet-class>marks</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc2</servlet-name>
<url-pattern>/mar</url-pattern>
</servlet-mapping>
</web-app>
import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class marks extends HttpServlet{


public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException
{
int i = [Link]([Link]("num1"));
int j = [Link]([Link]("num2"));
int k = [Link]([Link]("num3"));
int l = [Link]([Link]("num4"));
int m = [Link]([Link]("num5"));
int n = [Link]([Link]("num6"));
int total = i + j + k + l + m + n;
float avg = total / 6;

PrintWriter out = [Link]();


[Link]("Maths : " + i );
[Link]("English : " + j );
[Link]("Hindi : " + k);
[Link]("Science : " + l);
[Link]("Social Science : " + m);
[Link]("IT : " + n);
[Link]("Total Marks : "+ total);
[Link]("Average: "+avg);
}

}
GenericServlet class

In Servlet, GenericServlet is an abstract class. This class implements the servlet, ServletConfig and Se-
rializable interface. This class provides the implementation of most of the basic servlet methods. The
protocol of this class is independent as it can handle any type of request.
Class:

Methods of GenericServlet interface

Implemented Interfaces:

[Link], Servlet, ServletConfig


Constructor:

GenericServlet() : this constructor does nothing. Everything is initialized by the init method.
[Link]. Method Desciption
public void init(ServletConfig con- It is used for initialization of a
1
fig) servlet.
It is used for providing all the ser-
public abstract void service
vices for the incoming request.
2 (ServletRequest request,
When a user request then only it
ServletResponse response)
invokes.
It is used for destroying the
3 public void destroy()
servlet. It is invoked only once in a
public ServletConfig get- It is used to get the object of
4
ServletConfig() ServletConfig
It is used to get information about
5 public String getServletInfo()
writer, copyright etc of a servlet.
It is a very easy and convenient
6 public void init()
method for programmers.
public ServletContext get- It is used for getting object of a
7
ServletContext() servlet
public String getInitParameter It is used for getting all the pa-
8
(String name) rameter values from the given pa-

public Enumeration getInitParam- It is used for getting parameters


9
eterNames() which are defined in [Link] files
It is used for getting the name of
10 public String getServletName()
a servlet object.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>[Link]</title>
</head>
<body>
<form action="sal" align="center">
<h3 align="center">[Link]</h3>
<h3 align="center">--------------------------------------------------------</h3><br><br>
Enter Basic Salary <input type="text" name="num1"><br><br>
Enter Basic DA <input type="text" name="num2"><br><br>
Enter Basic HRA <input type="text" name="num3"><br><br>
<input type="submit">
</form>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="[Link]
xmlns="[Link] xsi:schemaLocation="http://
[Link]/xml/ns/javaee [Link]
id="WebApp_ID" version="4.0">
<display-name>Generic_Servlet</display-name>
<servlet>
<servlet-name>abc1</servlet-name>
<servlet-class>salary</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc1</servlet-name>
<url-pattern>/sal</url-pattern>
</servlet-mapping>
</web-app>
import [Link];
import [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class salary extends GenericServlet


{
/**
*
*/
private static final long serialVersionUID = 1L;

public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException


{
int i = [Link]([Link]("num1"));
int j = [Link]([Link]("num2"));
int k = [Link]([Link]("num3"));
int da = (j * i) / 100;
int hra = (k * i) / 100;
int g = i + da + hra;
PrintWriter out = [Link]();
[Link]("[Link]");
[Link]("DA : "+da);
[Link]("HRA : "+hra);
[Link]("Gross Salary : "+g);
}
}

Common questions

Powered by AI

The Servlet interface defines the methods init(), service(), and destroy(), which are called by the server during the servlet lifecycle. It is a low-level API that requires manual handling of HTTP-specific tasks. On the other hand, the HttpServlet class, which extends the Servlet interface, provides more HTTP-specific methods such as doGet(), doPost(), doHead(), doOptions(), doPut(), doTrace(), and doDelete(), automatically dispatching based on HTTP method types, making it more suitable for web applications handling HTTP requests .

The GenericServlet class is an abstract class that implements the Servlet and ServletConfig interfaces, allowing servlets to handle requests independent of the underlying protocol. Unlike the Servlet interface, which requires concrete implementation of its lifecycle methods, GenericServlet provides default implementations for a majority of methods, encouraging protocol-independent handling of requests through its service method. This class eases creation of general-purpose servlets that need not be confined to the HTTP protocol .

The RequestDispatcher interface facilitates the forwarding of requests from one servlet to another or the inclusion of content within a given response, vastly improving modularity and resource reusability in web applications. It allows multiple servlets to process different segments of the request, optimizing performance and supporting dynamic content generation. This capability is particularly valuable in complex web application architectures where separation of processing tasks among components enhances maintainability and scalability .

The doGet() method in the HttpServlet class is designed to handle HTTP GET requests, which are used to retrieve data from a server, whereas the doPost() method handles HTTP POST requests, which often include data submission from a client to the server for processing. Unlike GET, where parameters are included in the URL and often cached by browsers, POST encapsulates request data within the request body, providing a more secure way to send sensitive information .

Extending the HttpServlet class offers several advantages: it provides built-in HTTP request handling through methods like doGet() and doPost(), automatically dispatching requests based on HTTP method types. This design abstraction simplifies development by alleviating developers from implementing common HTTP-handling code and focusing more on application logic. Furthermore, HttpServlet includes session management and MIME-type handling, streamlining typical web application tasks .

In the Client-Servlet-Server interaction, a client sends a request, which the server receives and forwards to the servlet as a ServletRequest object. The servlet processes this request within its service method, accessing parameters and attributes, and generates a corresponding ServletResponse object to be sent back to the client. This model places emphasis on servlet methods like doGet() or doPost() (for HttpServlets) to handle data-specific HTPP requests, and also ensures dynamic interaction between the client and server, facilitating real-time web functionalities .

The HttpSession interface provides a mechanism for storing user-specific data across multiple requests, essential for maintaining state in stateless HTTP connections. It enhances web application functionality by allowing attributes to be stored and retrieved easily, supporting user-specific interactions such as login sessions or shopping cart contents without embedding state in URLs. This provides security and convenience, enabling sophisticated user experiences with persistent state management .

The init() method in the Servlet interface is crucial for initializing servlet configurations before handling requests, and it is invoked once during the servlet's lifecycle by the web container. Conversely, the destroy() method is called once before the servlet is taken out of service, allowing resources to be released appropriately. These methods ensure proper setup and teardown of resources to maintain efficient memory and resource management .

Init parameters allow configuration of a servlet's behavior by specifying values in a web deployment descriptor (web.xml). These parameters provide servlets with necessary configuration data at startup, minimizing hard-coded values and enhancing flexibility. By accessing these parameters through methods like getInitParameter(), servlets can be dynamically configured to perform tasks based on contextual requirements without recompilation, facilitating adaptive and environment-dependent behavior .

The servlet lifecycle consists of initialization, request processing, and destruction phases. It starts when the servlet is first loaded, invoking the init() method to perform setup tasks like resource allocation. During its active life, it processes client requests using the service() method. Finally, the destroy() method is called when the servlet is being destroyed, allowing it to clean up resources. These stages align directly with the methods defined in the Servlet interface, structuring the servlet's operational lifetime .

You might also like