Servlet Response

The ServletResponse is an in-built interface coming from javax.servlet package containing various methods that enable a servlet to respond to the client requests. There are various methods of ServletResponse interface, such as:

  • • getWriter(): Returns the PrintWriter object.
  • • void setCharacterEncoding(java.lang.String charset): Set the MIME charset (character encoding) of the response.
  • • void setContentLength(int len): It sets the length of the response body.
  • • void setContentType(java.lang.String type): Sets the type of the response data.
  • • void setBufferSize(int size): Sets the buffer size.
  • • int getBufferSize(): Returns the buffer size.
  • • void flushBuffer(): Forces any content in the buffer to be written to the client.
  • • boolean isCommitted(): Returns a boolean indicating if the response has been committed.
  • • void reset(): Clears the data of the buffer along with the headers and status code.
  • • java.lang.String getCharacterEncoding(): It returns the name of the MIME charset used in the response sent to the client.
  • • java.lang.String getContentType(): It returns the response content type. e.g. text, html etc.
  • • ServletOutputStream getOutputStream(): Returns a ServletOutputStream suitable for writing binary data in the response.

Let's see a demo program :

<!DOCTYPE html>
        <meta charset="ISO-8859-1">
        <title>Insert title here</title>
        <h2><u>Login Form:</u></h2><br><br>
        <form action="MyServlet" method="get">
                <tr><th>Username:</th><td><input type="text" name="uname">
                <tr><th>Password:</th><td><input type="password" name="pass">
                <tr><th><input type="submit" value="Submit"></th><td><input type="reset" value="Reset">
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
    public void doGet(HttpServletRequest request,HttpServletResponse response)
    throws IOException,ServletException
        PrintWriter out=response.getWriter();

        String s1=request.getParameter("uname");
        String s2=request.getParameter("pass");

        out.println("Successfully Logged In");
            out.println("Invalid Password");

About the Author

Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc