Java Reference
In-Depth Information
To send data to a browser, you create a servlet output stream associated with the browser
and then call the println( String ) method on that stream. Servlet output streams are
represented by the ServletOutputStream class, which is part of the javax.servlet
package. You can get one of these streams by calling the response object's
getOutputStream() method.
The following example creates a servlet output stream from an HttpServletResponse
object called response and then sends a short web page to that stream:
ServletOutputStream out = response.getOutputStream();
out.println(“<html>”);
out.println(“<body>”);
out.println(“<h1>Hello World!</h1>”);
out.println(“</body>”);
out.println(“</html>”);
Listing 21.1 contains a Java servlet that receives data from the form displayed in Figure
21.1.
LISTING 21.1
The Full Text of Rot13.java
1: import java.io.*;
2:
3: import javax.servlet.*;
4: import javax.servlet.http.*;
5:
6: public class Rot13 extends HttpServlet {
7:
8: public void doPost(HttpServletRequest req, HttpServletResponse res)
9: throws ServletException, IOException {
10:
11: String text = req.getParameter(“text”);
12: String translation = translate(text);
13: res.setContentType(“text/html”);
14: ServletOutputStream out = res.getOutputStream();
15: out.println(“<html>”);
16: out.println(“<body>”);
17: out.println(“<head><title>ROT-13 Translator</title></head>”);
18: out.println(“<h1>ROT-13 Translator</h1>”);
19: out.println(“<p>Text to translate:”);
20: out.println(“<form action=\”Rot13\” method=\”post\”>”);
21: out.println(“<textarea name=\”text\” ROWS=8 COLS=55>”);
22: out.println(translation);
23: out.println(“</textarea>”);
24: out.println(“<p><input type=\”submit\” value=\”translate\”>”);
25: out.println(“</form>”);
26: out.println(“</body>”);
27: out.println(“</html>”);
Search WWH ::




Custom Search