The servlet container is connected to the web server that receives Http Requests from client on a certain port. When client sends a request to web server, the servlet container creates HttpServletRequest
and HttpServletResponse
objects and passes them as an argument to the servlet service() method.
The response object allows you to format and send the response back to the client. First we will see the commonly used methods in the ServletReponse interface and then we will see an example.
Method of ServletResponse interface
1) String getCharacterEncoding()
: It returns the name of the MIME charset used in body of the response sent to the client.
2) String getContentType()
: It returns the response content type. e.g. text, html etc.
3) ServletOutputStream getOutputStream()
: Returns a ServletOutputStream suitable for writing binary data in the response.
4) java.io.PrintWriter getWriter()
: Returns the PrintWriter object.
5) void setCharacterEncoding(java.lang.String charset)
: Set the MIME charset (character encoding) of the response.
6) void setContentLength(int len)
: It sets the length of the response body.
7) void setContentType(java.lang.String type)
: Sets the type of the response data.
8) void setBufferSize(int size)
: Sets the buffer size.
9) int getBufferSize()
: Returns the buffer size.
10) void flushBuffer()
: Forces any content in the buffer to be written to the client.
11) boolean isCommitted()
: Returns a boolean indicating if the response has been committed.
12) void reset()
: Clears the data of the buffer along with the headers and status code.
To get the complete list of methods. Refer the official documentation.
Example:
In the below example, we have used setContentType() and getWriter() methods of ServletResponse interface.
index.html
<form action="mydetails" method="get"> User name: <input type="text" name="uname"> <input type="submit" value="login"> </form>
MyServletDemo.java
import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class MyServletDemo extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter pwriter=res.getWriter(); String name=req.getParameter("uname"); pwriter.println("User Details Page:"); pwriter.println("Hello "+name); pwriter.close(); } }
web.xml
<web-app> <servlet> <servlet-name>DemoServlet</servlet-name> <servlet-class>MyServletDemo</servlet-class> </servlet> <servlet-mapping> <servlet-name>DemoServlet</servlet-name> <url-pattern>/mydetails</url-pattern> </servlet-mapping> </web-app>
Output:
Screen 2:
Leave a Reply