Java Reference
In-Depth Information
Of course, we must also import the PrintWriter class with the following statement.
import java.io.PrintWriter;
That was the hard part. All you need to do now is write the HTML to the response object using out's (the print
writer's) println method.
Tutorial: Working with a Response Object
Let's look at the Response object:
1.
In MyServlet.java, add the following import statement:
import java.io.PrintWriter;
2.
In the doGet header, select the variable request, right-click on it, choose Refactor , and
then Rename .
3.
Specify req as the new name and press Enter.
4.
In the doGet header, rename response as resp.
5.
In the doPost header, rename the variables to req and resp also.
6.
In the doGet method, replace the System.out.println statement with the following
statements:
resp.setContentType("text/html");
PrintWriter out = new PrintWriter(resp.getOutputStream());
As explained earlier, these statements set the content type, create a print writer object, and assign it to a variable
called out.
7.
At the end of the doGet method, add the following statements to define a Web page's
header and title:
out.println("<HTML>");
out.println("<HEAD>");
out.println("<Title>MyServlet Get Response</Title>");
out.println("</HEAD>");
8.
At the end of the doGet method, add the following statements that define a Web page's
body and content:
out.println("<BODY>");
out.println("Howdy from MyServlet's doGet method!");
out.println("</BODY>");
out.println("</HTML>");
out.close();
Notice that the print writer's close method is called. The close method “flushes” the output stream and releases
any resources allocated to the output stream. Essentially, flushing ensures that the binary stream is written to the
response. (If you do not close the print writer, the response may not contain the HTML and a blank page would be
displayed.)
 
Search WWH ::




Custom Search