The final user interaction activity is to provide a response page to the client. The response page can be delivered by creating a servlet response page or JSP response page.
Generate the output page within a servlet by writing to the output stream. The recommended generation method depends on the output type.
Always specify the output MIME type using setContentType() before any output commences, as follows
response.setContentType("text/html"); |
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(); output.print(binary_data); |
Servlets can invoke JSP files in two ways, the include() method and the forward() method.
The include() method in the RequestDispatcher interface calls a JSP file and waits for it to return before continuing to process the interaction. The include() method can be called multiple times within a given servlet.
This example shows a JSP file using include():
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("JSP_URI"); dispatcher.include(request, response); ... //processing continues |
The forward() method in the RequestDispatcher interface handles the JSP interaction control. The servlet is no longer involved with the current interactions output after invoking forward() therefore only one call to the forward() method can be made in a particular servlet.
You cannot use the forward() method if you have already defined a PrintWriter or ServletOutputStream object.
This example shows a JSP page using forward():
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("JSP_URI"); dispatcher.forward(request, response); |
You identify which JSP noun to call by specifying a Universal Resource Identifier (URI). The path is a String describing a path within the ServletContext scope. You can also use the getRequestDispatcher() method in the request object that takes a String argument indicating a complete path.
Identify
The getRequestDispatcher method is similar to the RequestDispatcher in the ServletContext. The servlet container uses the information in the request object to transform the given relative path to a complete current servlet path, for example:
RequestDispatcher dispatcher = req.getRequestDispatcher(“foo/bar”);
In the previous example getRequestDispatcher does not start with “/”. In Web Server 6.1, this syntax resulted in a URI such as /webapp/foo/bar. In Sun Java System Web Server 7.0, the URI appears as /webapp/current_servlet_path/foo/bar
For more information about JSP pages, see Chapter 5, Developing JavaServer Pages.