This code is a part of simple HelloWorld Servlet file . Can anyone please explain the highlighted statement .... public void doGet(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException { rsp.setContentType("text/html"); PrintWriter out = rsp.getWriter(); out.println("<html>"); What does that statement do ??
PrintWriter is an abstract class for writing to character streams. Methods implement are write(char[], int, int), flush(), and close().Print formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
Thanks Pradeep. But Can you tell me how that downcasting works i.e calling a method from HttpResponse Object and assigning it to PrintWriter object PrintWriter out =rsp.getWriter();
The HttpServletResponse is an interface which can be used to write code to set an HTTP response header, set the content type of the response, acquire a text stream for the response, acquire a binary stream for the response, redirect an HTTP request to another URL, or add cookies to the response.
Thanks again.. But please clarify a few things ..I m novice to both java and servlets!!! rsp.setContentType("text/html"); PrintWriter out = rsp.getWriter(); out.println("<html>"); response object is used to set the header content type ,PrintWriter object to write to char streams ..But my question is "what happens in the mapping of PrintWriter out=rsp.getWriter()" Can you please give details a bit more?
Because... getWriter() simply returns a "PrintWriter" object that can send character text to the client. so ofcourse u have PrintWriter's object as a return value which u r assigning to a 'out' which is ev1 a object of printWriter class
One fairly simple implementation: PrintWriter getWriter() throws java.io.IOException { return new PrintWriter(socket.getOutputStream()); }
public java.io.PrintWriter getWriter() throws java.io.IOException Returns a PrintWriter object that can send character text to the client. The PrintWriter uses the character encoding returned by getCharacterEncoding(). If the response's character encoding has not been specified as described in getCharacterEncoding (i.e., the method just returns the default value ISO-8859-1), getWriter updates it to ISO-8859-1. Calling flush() on the PrintWriter commits the response. Either this method or getOutputStream() may be called to write the body, not both.
Pradeep.Printwriter is a Public Class Not an Abstract Class. So Please Dun't post unless you are sure about your Answer.