The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specific methods such as doGet, doPost, doHead, doTrace etc. The javax.servlet.http.HttpServlet class is a slightly more advanced base class than the GenericServlet.The HttpServlet class reads the HTTP request, and determines if the request is an HTTP GET, POST, PUT, DELETE, HEAD etc. and calls one the corresponding method.
Similar to the GenericServlet class this class is also abstract and we extend it make the SubClass work like a servlet. The SubClass must override one of the following methods:-
Popular Tutorials
service() method of HTTPServlet class is not abstract as was the case in the GenericServlet class and there is hardly any need to override that method as by default it contains the capability of deciding the type of the HTTP request it receives and based on that it calls the specific method to do the needful. For example, if an HTTP GET request calls the servlet then the service nethod of the HTTPServlet class determines the request type (it’ll find it to be GET) and subsequently calls doGet() method to serve the request.
To respond to e.g. HTTP GET requests only, you will extend the HttpServlet class, and override the doGet() method only. Here is an example:
public class SimpleHttpServlet extends HttpServlet { protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("<html><body>GET response</body></html>"); } }
If you want to handle both GET and POST request from a given servlet, you can override both methods, and have one call the other. Here is how:
public class SimpleHttpServlet extends HttpServlet { protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("GET/POST response"); } }
I would recommend you to use the HttpServlet instead of the GenericServlet whenever possible. HttpServlet is easier to work with, and has more convenience methods than GenericServlet.
Servlet Related Posts
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…