HttpServlet -


HttpServlet -

javax.servlet.http.HttpServlet is an abstract class that extends (inherit) GenericServlet class and also override service() method. Any normal class can be servlet by inheriting HttpServlet class. The class that inherit HttpServlet class must override at least one of the following methods -
1- doGet() - To handle HTTP protocol Get request.
2- doPost() - To handle HTTP protocol Post request.
3- doTrace() - To handle HTTP protocol Trace request.
4- doPut() - To handle HTTP protocol Put reuest.
etc.
In most of the cases we override doGet() or doPost() methods, as most of the times we use HTTP Get or Post requests.
There is no reason to override service() method, as service() method also handles HTTP requests by sending them to handler methods like doGet(), doPost(), doPut() etc.
HttpServlet is specific to HTTP protocol.

Fig: HttpServlet inherit GenericServlet


Example -

This example will show you how to create servlet using HttpServlet class.


1- Using NetBeans IDE -


Example 1 -

In this example, we create the servlet maually using HttpServlet.
Create a Java Web, Web Application Project in NetBeans.(Here we are using NetBeans IDE 8.2)
Note- If you are new to NetBeans IDE and do not know how to create Web Applications in NetBeans, then please refer to given link to learn how to download, install NetBeans IDE and how to create and run your first java web application - How to download and install NetBeans setup, and run your First Web Application.
Here we have given the name of project - 'HttpServletDemo' It will create the following project structure -



Now you have to follow the following steps -
1- index.html - As shown in above figure 'Web Pages' folder contains a file named 'index.html', It will be your default page(i.e. when you run your project, the output of this page will be displayed.).
Note- If you are using older version of NetBeans then your default page will be 'index.jsp'
Make changes to index.html as shown below -

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <a href="test">Click here to go to Http Servlet</a>
    </body>
</html>
       
2- Create a package named 'servs' in 'Source Packages' folder, then create a new class named MyFirstServ within that package as shown below -



Add the following code to 'MyFirstServ' class -

package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyFirstServ extends HttpServlet
{
 public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException
 {
     try
     {
         response.setContentType("text/html");   
         PrintWriter out = response.getWriter();
         out.println("<html>");
         out.println("<head>");
         out.println("<title>My FIrst Servlet</title>");
         out.println("</head>");
         out.println("<body>");
         out.println("<h1>HttpServlet Get method executes</h1>");
         out.println("</body>");
         out.println("</html>");
         
     }
     catch(Exception ex)
     {
         System.out.println(ex);
     }
 }
 
 public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException
 {
     try
     {
         response.setContentType("text/html");   
         PrintWriter out = response.getWriter();
         out.println("<html>");
         out.println("<head>");
         out.println("<title>My FIrst Servlet</title>");
         out.println("</head>");
         out.println("<body>");
         out.println("<h1>HttpServlet Post method executes</h1>");
         out.println("</body>");
         out.println("</html>");
         
     }
     catch(Exception ex)
     {
         System.out.println(ex);
     }
 }
 
}    
Program Description -
  • To convert 'MyFirstServ' class into servlet, class extends 'HttpServlet' class. As we already know in case of HttpServlet we do not need to override service() method directly, we override doGet(), doPost(), doPut() etc methods depending upon HTTP request type. For HTTP Get request doGet() method will execute, for HTTP Post request doPost() will execute and so on.
  • Note that Servlet's do not have main() method, Whenever request came to servlet, it is the doGet() or doPost() etc methods gets executed depending upon HTTP request type.
  • doGet() and doPost() methods has 2 parameters- javax.servlet.http.HttpServletRequest request and javax.servlet.http.HttpServletResponse response - these are the direct subclasses of ServletRequest and ServletResponse interfaces respectively. These corresponds to client request and response generated by server for the coming request respectively.
  • response.setContentType("text/html"); - HttpServletResponse has method setContentType() that inform the client browser, what type of data is coming in response from server, so that browser can do the right things, for example launch a helper app like video player or pdf reader etc.
  • PrintWriter out = response.getWriter(); - java.io.PrintWriter object is required to write HTML text , we can get it from ServletResponse.
  • out.println() - PrintWriter has print() and println() methods that are used to write HTML text on web pages.


3- web.xml (Deployment Descriptor) -
  • When we deploy our application on server, we need to create a XML file (web.xml), to tell the server, how to run our Servlet,s. This web.xml file is also called Deployment Descriptor.
  • In this file we have to put all the information regarding our servlets like servlet name, servlet class, url etc. Basically the main purpose of this is to create a mapping between client known public url('test' in our example) and servlet class name('MyFirstServ' in our example).
  • In addition to servlet information , web.xml file also used to contain several other information that will be discussed ahead.
To add Web.XML in your project, follow the following steps -
` Right click on your project go to New -> Other, It will open a window as shown below -


Click Next -> Finish, and it will create a web.xml file in Configuration Files as shown below -



For mapping client known public url('test' in our example) and servlet class name('MyFirstServ' in our example), we need to define following 2 XML tags -
<servlet>
It maps internal name defined in web.xml to your original servlet class name.
It contains two sub tags within it -
1- <servlet-name> - It contain internal name defined in web.xml (We used 'demo' in our example). This name can be anything, whatever you want.
2- <servlet-class> - It contain fully qualified servlet class name with package name ('servs.MyFirstServ' in our example).
<servlet>
   <servlet-name>demo</servlet-name>
   <servlet-class>servs.MyFirstServ</servlet-class>
</servlet>   
<servlet-mapping>
It maps internal name defined in web.xml to client known public url.It contains two sub tags within it -
1- <servlet-name> - It will be the same as we defined in <servlet> tag(i.e. demo in our example). 2- <url-pattern> - It will be the client known public url ('/test' in our example, because in index.html we use 'test' as hyperlink in anchor tag).
<servlet-mapping>
  <servlet-name>demo</servlet-name>
  <url-pattern>/test</url-pattern>
</servlet-mapping>         
Add the above defined both tags in web.xml within web-app as follows -
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	 version="3.1">
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    
    <servlet>
        <servlet-name>demo</servlet-name>
        <servlet-class>servs.MyFirstServ</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>demo</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
    
</web-app>  

3.1 - Use of Annotation in place of web.xml for Servlet Mapping -

Java defines a package named "javax.servlet.annotation" that provides us various annotations we can use to declare servlet, listeners, filters etc.
For servlet mapping, it defines a annotation named "javax.servlet.annotation.WebServlet". We can use it to define url pattern of our servlet. This annotation gets processed by web container at the deployment time of our servlet.
To use annotation make the following chnages to "MyFirstServ" class -
package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;

@WebServlet("/test")   // "/test" will be the url pattern of this servlet class
public class MyFirstServ extends HttpServlet
{
 public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException
 {
     try
     {
         response.setContentType("text/html");   
         PrintWriter out = response.getWriter();
         out.println("<html>");
         out.println("<head>");
         out.println("<title>My FIrst Servlet</title>");
         out.println("</head>");
         out.println("<body>");
         out.println("<h1>HttpServlet Get method executes</h1>");
         out.println("</body>");
         out.println("</html>");
         
     }
     catch(Exception ex)
     {
         System.out.println(ex);
     }
 }
 
 public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException
 {
     try
     {
         response.setContentType("text/html");   
         PrintWriter out = response.getWriter();
         out.println("<html>");
         out.println("<head>");
         out.println("<title>My FIrst Servlet</title>");
         out.println("</head>");
         out.println("<body>");
         out.println("<h1>HttpServlet Post method executes</h1>");
         out.println("</body>");
         out.println("</html>");
         
     }
     catch(Exception ex)
     {
         System.out.println(ex);
     }
 }
 
}



Now we do not need to add servlet information in web.xml file.
Note - This method can only be used with HttpServlet's.
4- Now run your project and it will show you the default page (index.html) on your web browser as follows -



Click on the link and it will show you the following output -



Note- It executes doGet() method of servlet, because by default HTTP make a Get request.

Example 2 -

Using NetBeans predefined sample Servlet to create HttpServlet.
In place of creating Servlet manually, we can also use sample Servlet provided by NetBeans. We can use it as follows -

1- Delete the Servlet and web.xml file created in Example1.
2- Right click on servs package, go to New -> Serlet.



3- It will open a New Servlet Windows. Enter the name of Servlet (MyFirstServ in our example), and click Next.



4- Checked the "Add information to deployment descriptor check box", And enter the Servlet name and URL pattern according to your requirement (Servlet name - demo and URL pattern - /test in our example). and click on Finish button.



5- And it will create a Servlet for us like this -

package servs;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyFirstServ extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet MyFirstServ</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet MyFirstServ at " + request.getContextPath() + "</h1>");
            // Code will goes here.
            out.println("</body>");
            out.println("</html>");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }


    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
    

Note that its the same servlet as we created manually, the only difference is that, NetBeans created its own method named processRequest() that will be called each time, whether the request is for doGet() or for doPost(), because both the method here makes call to processRequest(). We can make changes in this Servlet according to our requirements.

6- Browse to Configuration Files and you will see that web.xml file already available there. Open web.xml and you will find that Servlet information is already available there, that we had entered at the time servlet creation.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>demo</servlet-name>
        <servlet-class>servs.MyFirstServ</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>demo</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>
    

7- Now run your project and it will show you the following output -

Click on the link and it will show you the following output -



2- Using Eclipse IDE -


Example 1 -

In this example, we create the servlet manually using HttpServlet.

Create a New Dynamic Web Project in Eclipse.(Here we are using Eclipse Oxygen IDE)
Note- If you are new to Eclipse IDE and do not know how to create Web Applications in Eclipse, then please refer to given link to learn how to download, install Eclipse IDE and how to create and run your first java web application - How to download and install Eclipse setup, and run your First Web Application.
Here we have given the name of project - 'HttpServletDemo'.
It will create the following project structure -



Now you have to follow the following steps -
1- index.html - Right Click on your Project and add a 'index.html' page. And add the following code -
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="test">Click here to go to Htttp Servlet</a>
</body>
</html>        
2- Create a package named 'servs' in 'src' folder, then create a new class named MyFirstServ within that package as shown below -



Add the following code to 'MyFirstServ' class -
package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyFirstServ extends HttpServlet
{
 public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException
 {
     try
     {
         response.setContentType("text/html");   
         PrintWriter out = response.getWriter();
         out.println("<html>");
         out.println("<head>");
         out.println("<title>My FIrst Servlet</title>");
         out.println("</head>");
         out.println("<body>");
         out.println("<h1>HttpServlet Get method executes</h1>");
         out.println("</body>");
         out.println("</html>");
         
     }
     catch(Exception ex)
     {
         System.out.println(ex);
     }
 }
 
 public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException
 {
     try
     {
         response.setContentType("text/html");   
         PrintWriter out = response.getWriter();
         out.println("<html>");
         out.println("<head>");
         out.println("<title>My FIrst Servlet</title>");
         out.println("</head>");
         out.println("<body>");
         out.println("<h1>HttpServlet Post method executes</h1>");
         out.println("</body>");
         out.println("</html>");
         
     }
     catch(Exception ex)
     {
         System.out.println(ex);
     }
 }
 
}
    
Program Description -
  • To convert 'MyFirstServ' class into servlet, class extends 'HttpServlet' class. As we already know in case of HttpServlet we do not need to override service() method directly, we override doGet(), doPost(), doPut() etc methods depending upon HTTP request type. For HTTP Get request doGet() method will execute, for HTTP Post request doPost() will execute and so on.
  • Note that Servlet's do not have main() method, Whenever request came to servlet, it is the doGet() or doPost() etc methods gets executed depending upon HTTP request type.
  • doGet() and doPost() methods has 2 parameters- javax.servlet.http.HttpServletRequest request and javax.servlet.http.HttpServletResponse response - these are the direct subclasses of ServletRequest and ServletResponse interfaces respectively. These corresponds to client request and response generated by server for the coming request respectively.
  • response.setContentType("text/html"); - HttpServletResponse has method setContentType() that inform the client browser, what type of data is coming in response from server, so that browser can do the right things, for example launch a helper app like video player or pdf reader etc.
  • PrintWriter out = response.getWriter(); - java.io.PrintWriter object is required to write HTML text , we can get it from ServletResponse.
  • out.println() - PrintWriter has print() and println() methods that are used to write HTML text on web pages.

3- web.xml (Deployment Descriptor) -
  • When we deploy our application on server, we need to create a XML file (web.xml), to tell the server, how to run our Servlet,s. This web.xml file is also called Deployment Descriptor.
  • In this file we have to put all the information regarding our servlets like servlet name, servlet class, url etc. Basically the main purpose of this is to create a mapping between client known public url('test' in our example) and servlet class name('MyFirstServ' in our example).
  • In addition to servlet information , web.xml file also used to contain several other information that will be discussed ahead.
For mapping client known public url('test' in our example) and servlet class name('MyFirstServ' in our example), we need to define following 2 XML tags -
<servlet>
It maps internal name defined in web.xml to your orignal servlet class name.
It contains two sub tags within it -
1- <servlet-name> - It contain internal name defined in web.xml (We used 'demo' in our example). This name can be anything, whatever you want.
2- <servlet-class> - It contain fully qualified servlet class name with package name ('servs.MyFirstServ' in our example).
<servlet>
   <servlet-name>demo</servlet-name>
   <servlet-class>servs.MyFirstServ</servlet-class>
</servlet>   
<servlet-mapping>
It maps internal name defined in web.xml to client known public url.It contains two sub tags within it -
1- <servlet-name> - It will be the same as we defined in <servlet> tag(i.e. demo in our example). 2- <url-pattern> - It will be the client known public url ('/test' in our example, because in index.html we use 'test' as hyperlink in anchor tag).
<servlet-mapping>
  <servlet-name>demo</servlet-name>
  <url-pattern>/test</url-pattern>
</servlet-mapping>         
Add the above defined both tags in web.xml within web-app as follows -
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	 version="3.1">
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    
    <servlet>
        <servlet-name>demo</servlet-name>
        <servlet-class>servs.MyFirstServ</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>demo</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
    
</web-app>  

3.1 - Use of Annotation in place of web.xml for Servlet Mapping -

Java defines a package named "javax.servlet.annotation" that provides us various annotations we can use to declare servlet, listeners, filters etc.
For servlet mapping, it defines a annotation named "javax.servlet.annotation.WebServlet". We can use it to define url pattern of our servlet. This annotation gets processed by web container at the deployment time of our servlet.
To use annotation make the following chnages to "MyFirstServ" class -
package servs;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;

@WebServlet("/test")   // "/test" will be the url pattern of this servlet class
public class MyFirstServ extends HttpServlet
{
 public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException
 {
     try
     {
         response.setContentType("text/html");   
         PrintWriter out = response.getWriter();
         out.println("<html>");
         out.println("<head>");
         out.println("<title>My FIrst Servlet</title>");
         out.println("</head>");
         out.println("<body>");
         out.println("<h1>HttpServlet Get method executes</h1>");
         out.println("</body>");
         out.println("</html>");
         
     }
     catch(Exception ex)
     {
         System.out.println(ex);
     }
 }
 
 public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException
 {
     try
     {
         response.setContentType("text/html");   
         PrintWriter out = response.getWriter();
         out.println("<html>");
         out.println("<head>");
         out.println("<title>My FIrst Servlet</title>");
         out.println("</head>");
         out.println("<body>");
         out.println("<h1>HttpServlet Post method executes</h1>");
         out.println("</body>");
         out.println("</html>");
         
     }
     catch(Exception ex)
     {
         System.out.println(ex);
     }
 }
 
}



Now we do not need to add servlet information in web.xml file.
Note - This method can only be used with HttpServlet's.

4- Now run your project and it will show you the default page (index.html) on your web browser as follows -



Click on the link and it will show you the following output -



Note- It executes doGet() method of servlet, because by default HTTP make a Get request.

Example 2 -

Using Eclipse predefined sample Servlet to create HttpServlet.
In place of creating Servlet manually, we can also use sample Servlet provided by Eclipse. We can use it as follows -

1- Delete the Servlet and web.xml file created in Example1.
2- Right click on servs package and go to New -> Servlet.



3- It will open Create Servlet windows, enter the name of servlet (MyFirstServ in our example)and press Next button.



4- Next windows will ask for URL Mapping, by default URL pattern will be the same as your servlet name. To change it, click Edit button.



5- Enter the desired URL Pattern and click Finish



6- And it wil create a Servlet for us. Make changes to your Servlet according to following -
package servs;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class MyFirstServ
 */
@WebServlet("/test")
public class MyFirstServ extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
 public MyFirstServ() {
   super();
   // TODO Auto-generated constructor stub
 }

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

 try
  {
     response.setContentType("text/html");   
     PrintWriter out = response.getWriter();
     out.println("<html>");
     out.println("<head>");
     out.println("<title>My FIrst Servlet</title>");
     out.println("</head>");
     out.println("<body>");
     out.println("<h1>HttpServlet Get method executes</h1>");
     out.println("</body>");
     out.println("</html>");
 
   }
  catch(Exception ex)
   {
     System.out.println(ex);
   }
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
   {
    response.setContentType("text/html");   
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>My FIrst Servlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>HttpServlet Post method executes</h1>");
    out.println("</body>");
    out.println("</html>");
         
  }
catch(Exception ex)
 {
   System.out.println(ex);
 }
}

}        

7- There is no need to create web.xml file as Eclipse by default makes use of annotation for url pattern.
8- Now run your project and it will show you the same output as in Example1.