Sun Java System Web Server 6.1 SP7 Programmer's Guide to Web Applications

Delivering Client Results

The final user interaction activity is to provide a response page to the client. The response page can be delivered in two ways, as described in the following topics:

Creating a Servlet Response Page

Generate the output page within a servlet by writing to the output stream. The recommended way to do this depends on the output type.

Always specify the output MIME type using setContentType() before any output commences, as in this example:



For textual output, such as plain HTML, create a PrintWriter object and then write to it using println. For example:

PrintWriter output = response.getWriter();
output.println("Hello, World\n");


For binary output, write to the output stream directly by creating a ServletOutputStream object and then write to it using print(). For example:

ServletOutputStream output = response.getOutputStream();


Creating a JSP Response Page

Servlets can invoke JSPs in two ways, the include() method and the forward() method:

RequestDispatcher dispatcher =
 dispatcher.include(request, response);
   ... //processing continues


Note –

You cannot use the forward() method if you have already defined a PrintWriter or ServletOutputStream object.

This example shows a JSP using forward():

RequestDispatcher dispatcher =
 dispatcher.forward(request, response);


Note –

Identify which JSP to call by specifying a Universal Resource Identifier (URI). The path is a String describing a path within the ServletContext scope. There is also a getRequestDispatcher() method in the request object that takes a String argument indicating a complete path. For more information about this method, see the Java Servlet 2.3 specification, section 8.

For more information about JSPs, see Chapter 4, Using JavaServer Pages.