Servlet API
Servlet API consists of two important packages that encapsulates all the important classes and interface, namely :
- javax.servlet
- javax.servlet.http
Some Important Classes and Interfaces of javax.servlet
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 javax.servlet.http
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 interface. 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
S.No. |
Method |
Description |
1. |
public void init(ServletConfigconfig) |
It is used for initializing the servlet. It is invoked only once by the web container in a servlet life cycle. |
2. |
public void service(ServletRequestreq, ServletResponse res) |
It is used for providing a response to all the incoming request. It is invoked every time by the web container for each request. |
3. |
public void destroy() |
It is used for destroying the servlet. It is invoked only once in a life cycle of a servlet. |
4. |
public ServletConfiggetServletConfig() |
It is used to get the object of ServletConfig. |
5. |
Public String getServletInfo() |
It is used to get information about writer, copyright etc of a servlet. |
Example of Servlet interface on Eclipse
For creating a servlet interface below is the directory structure of the program:
Following are the steps for creating the program.
Step 1: Create a dynamic project on eclipse by clicking on
File => New => Dynamic Web Project
Step 2: Now create an HTML file.
Right-click on the project and then click on HTML file. Give the name of the file and then click on the finish button.
And write the below code.
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>studytonight => servlet interface example</title>
</head>
<body>
<h1>studytonight.com</h1><br><br>
************************************<br><br>
<h3><a href="demo">Click here to proceed...</a></h3><br><br>
************************************<br><br>
</body>
</html>
Step 3: Now add the below code in web.xml file.
web.xml file is a deployment descripter. Here we have all the configurations.
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-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>
Step 4: Now next create a servlet. For this create a class. Give the package name and the class name.
Now add the below code in the class file.
DemoServlet.java
import java.io.*;
import javax.servlet.*;
public class DemoServlet implements Servlet{
ServletConfig config=null;
public void init(ServletConfig config){
this.config=config;
}
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter pwriter=res.getWriter();
pwriter.print("<html>");
pwriter.print("<body>");
pwriter.print("<h1>Hello Welcome to studytonight. This example is of servlet interface. </h1>");
pwriter.print("</body>");
pwriter.print("</html>");
}
public void destroy(){
System.out.println("servlet destroy");
}
public ServletConfig getServletConfig(){
return config;
}
public String getServletInfo(){
return "studytonight.com";
}
}
Now, Run the code.
To run the code, right-click on the project and select Run As => Run on Server.
Below is the index.html page. Click on the link for landing in the servlet page.
This is the servlet page.
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
S.No. |
Method |
Description |
1 |
public void service(ServletRequest req,ServletResponse res) |
It is used for securing the service method by creating objects of request and response. |
2 |
protected void service(HttpServletRequest req, HttpServletResponse res) |
It is used for receiving a service method. |
3 |
protected void doGet(HttpServletRequest req, HttpServletResponse res) |
It is invoked by the web container and it is used for handling the GET request. |
4 |
protected void doPost(HttpServletRequest req, HttpServletResponse res) |
It is invoked by the web container and it handles the POST request. |
5 |
protected void doHead(HttpServletRequest req, HttpServletResponse res) |
It is invoked by the web container and it handles the HEAD request. |
6 |
protected void doOptions(HttpServletRequest req, HttpServletResponse res) |
It is invoked by the web container and it handles the OPTIONS request. |
7 |
protected void doPut(HttpServletRequest req, HttpServletResponse res) |
It is invoked by the web container and it handles the OPTIONS request. |
8 |
protected void doTrace(HttpServletRequest req, HttpServletResponse res) |
It is invoked by the web container and it handles the TRACE request |
9 |
protected void doDelete(HttpServletRequest req, HttpServletResponse res) |
It is invoked by the web container and it handles the DELETE request. |
10 |
protected long getLastModified(HttpServletRequest req) |
It is used for getting the time of last modified HttpServletRequest. |
Example of HttpServlet class on Eclipse
For creating a HttpServlet class below is the directory structure of the program:
Following are the steps for creating the program.
Step 1: Create a dynamic project on eclipse by clicking on
File => New => Dynamic Web Project
Step 2: Now create an HTML file.
Right-click on the project and then click on HTML file. Give the name of the file and then click on the finish button.
And write the below code.
Demo.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="mar" align="center">
<h3 align="center">studytonight.com</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>
Step 3: now add the below code in web.xml file.
web.xml file is a deployment descripter. Here we have all the configurations.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/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>
Step 4: Now next create a servlet. For this create a class. Give the package name and the class name.
Add the below code in the class file.
marks.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
public class marks extends HttpServlet{
public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException
{
int i = Integer.parseInt(req.getParameter("num1"));
int j = Integer.parseInt(req.getParameter("num2"));
int k = Integer.parseInt(req.getParameter("num3"));
int l = Integer.parseInt(req.getParameter("num4"));
int m = Integer.parseInt(req.getParameter("num5"));
int n = Integer.parseInt(req.getParameter("num6"));
int total = i + j + k + l + m + n;
float avg = total / 6;
PrintWriter out = res.getWriter();
out.println("Maths : " + i );
out.println("English : " + j );
out.println("Hindi : " + k);
out.println("Science : " + l);
out.println("Social Science : " + m);
out.println("IT : " + n);
out.println("Total Marks : "+ total);
out.println("Average: "+avg);
}
}
Now, Run the code.
To run the code, right-click on the project and select Run As => Run on Server.
Below is the index.html page. Click on the link for landing in the servlet page.
This is the servlet page.
GenericServlet class
In Servlet, GenericServlet is an abstract class. This class implements the servlet, ServletConfig and Serializable 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:
java.io.Serializable, Servlet, ServletConfig
Constructor:
GenericServlet() : this constructor does nothing. Everything is initialized by the init method.
S.NO. |
Method |
Desciption |
1 |
public void init(ServletConfig config) |
It is used for initialization of a servlet. |
2 |
public abstract void service(ServletRequest request, ServletResponse response) |
It is used for providing all the services for the incoming request. When a user request then only it invokes. |
3 |
public void destroy() |
It is used for destroying the servlet. It is invoked only once in a life cycle of a servlet. |
4 |
public ServletConfig getServletConfig() |
It is used to get the object of ServletConfig |
5 |
public String getServletInfo() |
It is used to get information about writer, copyright etc of a servlet. |
6 |
public void init() |
It is a very easy and convenient method for programmers. |
7 |
public ServletContext getServletContext() |
It is used for getting object of a servlet |
8 |
public String getInitParameter(String name) |
It is used for getting all the parameter values from the given parameter names. |
9 |
public Enumeration getInitParameterNames() |
It is used for getting parameters which are defined in web.xml files |
10 |
public String getServletName() |
It is used for getting the name of a servlet object. |
11 |
public void log(String msg) |
It is used for writing a message in a servlet log file. |
12 |
public void log(String msg, Throwable t) |
It is used for writing a message in a servlet log file and stack trace. |
Example of GenericServlet interface on Eclipse
For creating a GenericServlet class below is the directory structure of the program:
Following are the steps for creating the program
Step 1: Create a dynamic project on eclipse by clicking on
File => New => Dynamic Web Project
Step 2: Now create an HTML file.
And write the below code.
Demo2.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Studytonight.com</title>
</head>
<body>
<form action="sal" align="center">
<h3 align="center">studytonight.com</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>
Step 3: now add the below code in web.xml file.
web.xml file is a deployment descripter. Here we have all the configurations.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" 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>
Step 4: Now next create a servlet. For this create a class. Give the package name and the class name.
Add the below code in the class file.
salary.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class salary extends GenericServlet
{
/**
*
*/
private static final long serialVersionUID = 1L;
public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException
{
int i = Integer.parseInt(req.getParameter("num1"));
int j = Integer.parseInt(req.getParameter("num2"));
int k = Integer.parseInt(req.getParameter("num3"));
int da = (j * i) / 100;
int hra = (k * i) / 100;
int g = i + da + hra;
PrintWriter out = res.getWriter();
out.println("studytonight.com");
out.println("DA : "+da);
out.println("HRA : "+hra);
out.println("Gross Salary : "+g);
}
}
Now, Run the code.
To run the code, right-click on the project and select Run As => Run on Server.
Below is the demo2.html page. Click on the link for landing in the servlet page.
This is the servlet page.