ServletResponse vs HttpServletResponse

When the client sends a request to the Web server, the server loads the concerned Servlet and executes the service() method. In the process of execution, the container creates objects of ServletRequest and ServletResponse and passes them to the service() method. This is discussed in First Example – Login Screen Validation.

ServletResponse vs HttpServletResponse

ServletResponse vs HttpServletResponse

Observe, HttpServletResponse is derived from ServletResponse.

Following table gives the differences between ServletResponse and HttpServletResponse.

ServletResponse HttpServletResponse
Belongs to javax.servlet package Belongs to javax.servlet.http package
sub interface of ServletResponse
Comes with many methods like getWriter() etc. It inherits all the methods of ServletResponse and apart adds its own like encodeURL() and sendRedirect() etc.
Used in combination with GenericServlet Used in combination with HttpServlet
Protocol independent Protocol dependent and specific for HTTP protocol
When HTTP was not used, in earlier days, when a request came from client, Web container used to create an object of ServletResponse and passed to service() method. When a request comes from client using HTTP protocol, Web container creates an object of HttpServletResponse and passes to service() method

Something more to know about ServletResponse vs HttpServletResponse:

1. With HTTP protocol also, GenericServlet and ServletResponse can be used. The container creates an object of HttpServletResponse (because request is coming from client using HTTP) and passes to ServletResponse, if ServletResponse is required by the container. The actual implementation is left to the Web server designers.

2. ServletResponse and HttpServletResponse are interfaces with all abstract methods. The implementation part of abstract methods in the subclasses is written by the Web server designers. The implementation is completely dependent on the Web server. For example, the Weblogic server designer may write his own subclass of ServletResponse as WeblogicServletResponse and can pass to service() method. The extra behaviour and properties are server dependent.

Leave a Comment

Your email address will not be published.