Learn about HttpServlet in Java

HttpServlet is one of the objects of the Java Servlet API that enables us to build web-based applications. How is it in details? Let’s find out in this tutorial.

First, I will create a Maven project for the web application as an example, as follows:

Learn about HttpServlet in Java

If you guys do not know how to create Maven project for web application, you can refer to this tutorial.

Maven Jetty Plugin to run for example:

OK, back to the main topic for this tutorial.

HttpServlet is an abstract class located in the Java Servlet API’s javax.servlet.http package. It extends from another abstract class called GenericServlet and this GenericServlet class is the implementation of the Servlet interface, the main interface for defining the servlet of the Java Servlet API.

Using this HttpServlet object, we can build Java web applications to handle client requests with HTTP methods such as GET, POST, HEAD, PUT, DELETE, TRACE and OPTIONS. When the client sends a request to the web server container, the service() method in the HttpServlet object will process the request. Depending on the HTTP method the client sends, subsequent processing is done by the doGet(), doPost(), doHead(), doPut(), doDelete(), doTrace(), and doOptions() methods.

We can override the doGet(), doPost(), doHead(), doPut(), doDelete(), doTrace(), and doOptions() methods to process the request as we wish. Try to apply this to our example.

Now, I’m going to add a new class called HelloWorldServlet in the com.huongdanjava.httpservlet package:

Learn about HttpServlet in Java

with the following content:

As you can see, my HelloWorldServlet class extends from the HttpServlet class, and in this HelloWorldServlet class, I overrun the doGet() method to process the request with the HTTP method GET. Simply return the client to an HTML page with the content “<h1>Hello World from Huong Dan Java</ h1> “.

To declare this servlet with web container, we have two ways:

  • Declare using the Java Servlet API’s @WebServlet annotation in this Servlet class.
  • Declare this Servlet in the Deployment Descriptor file for the web application, web.xml located in the /src/main/webapp/WEB-INF directory.

The priority that the web container will process first is the configuration that we declare in the web.xml file, then the configuration of the @WebServlet annotation. I will talk more about these two ways in the incoming tutorials.

For simplicity, we will use the @WebServlet annotation by rename the web.xml file in the /src/main/webapp/WEB-INF directory to web1.xml and declare using the @WebServlet annotation in the HelloWorldServlet class as follows:

At this point, if you run the application, you will see the results as follows:

Learn about HttpServlet in Java


Add Comment