ServletResponse Interface in Servlet

As we have discussed in the previous article about ServletRequest Interface in Servlet. Now, If the client requests the server, the server has to respond to the client so for that, we used ServletResponse Interface. So In this article, we will discuss ServletResponse Interface, its method, etc.

What is ServletResponse Interface?

The Servlet/web container gets the request from the client, it creates a request and response object and passes it to the service() method as an argument. This response object is used to send a response back to the client. So, ServletResponse is used as an object to give a response to the client.

Methods in ServletResponse Interface

  • String getCharacterEncoding(): This method returns the name of MIME used in the body of the response.
    • MIME: It is a Multipurpose Internet Mail Extension¬†extends the format of email messages to support text in character sets other than ASCII.
  • String getContentType():This method returns the type of response content.
  • ServletOutputStream getOutputStream():This methods returns the binary data in a MIME body response.
  • PrintWriter getWriter(): This method returns the object that can send text data to the client.
  • void setCharacterEncoding(String charset): This method sets the MIME charset of response.
    • charset: It is a string of character encoding.
  • void setContentLength(int len): This method sets the length of the response.
    • len: Length of the response in integer.
  • void setContentType(String type): This method sets the type of response data.
  • void setBufferSize(int size): This method sets the buffer size.
  • int getBufferSize():This method returns the buffer size.
  • void flushBuffer(): This method forces content in the buffer to be written to the client.
  • boolean isCommitted(): This method returns boolean that indicates if the response is committed.
  • void reset(): This method returns the data of buffer with header and status code.

Let’s see the example of ServletResponse Interface

In this example we will use setContentType() method and getWriter() method.

index.html

Example.java

web.xml

Output