Writing results back to the client

With servlets, you can return dynamic content to the requesting client. That output is generated based on information passed to the servlet or on information that the servlet calculates. For example, a servlet can use a passed form attribute (accessed using the request object) to return formatted database data. Alternatively, if the application has a method of maintaining user preferences, the servlet might set the display color of the browser based on stored preference information.

You return information through the HTTP response, as follows:

Working with special characters

When using print and println methods of the PrintWriter object, you must take special precautions when using quotation marks. Escape the special character with backslashes, as shown in the following examples:

out.println("<INPUT TYPE=\"Submit\" VALUE=\"Submit\"></FORM>");

To include quotation marks in the output, you can use HTML entities. These are interpreted by the browser for display and not interpreted by the servlet for processing. The following example shows the user of HTML entities for quotation marks:

out.println("<B>&quot;Danger here,&quot; he said.</B>");

This example renders the following in the browser:

"Danger here," he said.

For a list of HTML entities, see http://www.ramsch.org/martin/uni/fmi-hp/iso8859-1.html.

Setting headers

The HttpServletResponse object API includes several methods that set HTTP headers for the response object. These methods replace the existing values of the current headers, if any. Some of these methods are inherited from the ServletResponse object.

The following table describes these methods:
Method
Description
setHeader(String name, String value)
Sets any header that takes a String and that does not have a convenience method. If the value is an int, use the setIntHeader method.
To set the Refresh header, use the following code:
response.setHeader("Refresh", "15");
setDateHeader(String name, long date)
Sets the Date header.
setIntHeader(String name, int value)
Sets any header that takes an int value and that does not have a convenience method. If the value is a String, use the setHeader method.
To set the Expires header use the following code:
response.setIntHeader("Expires", -1);
setContentLength(int length)
Sets the Content-Length header to the indicated number of bytes. For example:
response.setContentLength(data.length);

The HttpServletResponse interface inherits this method from ServletResponse. You typically do not change this header.
setContentType()
Sets the Content-Type header. Content-Type identifies the MIME type of the response document and the character set encoding. To set the Content-Type header, use the following code:
response.setContentType("text/html; charset=Shift_JIS");

The default MIME type is text/plain. Some common MIME types include:
  • HTML format (.htm or .html): text/html
  • Adobe Portable Document (pdf): application/pdf
  • Microsoft Word (.doc): application/msword
  • Microsoft Excel (.xls): application/msexcel
  • Microsoft Powerpoint (.ppt): application/ms-powerpoint
  • Realaudio (.rm, .ram): audio/x-pn-realaudio
  • Text format (.txt): text/txt
  • Zipped files (.zip): application/zip
To download a list of registered MIME types, see ftp://ftp.isi.edu/in-notes/iana/assignments/media-types/.
For information on setting character sets, see Chapter 3, "Introduction to internationalization and localization".
setContentLength(int len)
Sets the Content-Length header.
setLocale(Locale locale)
Sets the Content-Language header and charset value of the Content-Type header. The default is the locale of the server's system.
For more information on using internationalization techniques in web applications, see Chapter 3, "Introduction to internationalization and localization".
addCookie(Cookie cookie)
Sets the Set-Cookie header. You can add multiple cookies to a response. For more information on using cookies, see "Working with cookies".
sendRedirect(String location)
Sets the Location header and status code to 302 (Found). You can provide a relative or absolute URI; for example:
response.sendRedirect("http://www.hamsteak.com/index.html");

If you provide a relative URL, JRun builds an absolute URI before redirecting the request.The servlet API also includes a RequestDispatcher that provides a convenient way of redirecting requests.
For more information, see "Passing control".
setStatus(int sc)
Sets the status code for the response document. The status codes are as follows:
  • 1xx: Informational����A valid request was received.
  • 2xx: Success����The request is valid and the response was successful.
  • 3xx: Redirection����The request cannot be fulfilled without more information.
For more information on specific status codes, see the HTTP specification.
sendError(int sc)
Sends an error to the browser using the specified status code. The error status codes are as follows:
  • 4xx: Client Error����The request is invalid.
  • 5xx: Server Error����The server failed to fulfill a request.
For more information on specific status codes, see the HTTP specification.

The response object also includes equivalent addXxxxx methods that add new headers to to the response rather than replacing the existing headers. For more information, see the servlet API.

The following code example sets response headers and prints a list of the request headers:

...
resp.setContentType("text/html");
int sc=200;
resp.setStatus(sc);
resp.setHeader("Cache-Control", "no-cache,must-revalidate");
resp.setHeader("Pragma", "no-cache");
resp.setHeader("Cache-Control", "no-store");
resp.setDateHeader("max-age", 0);
resp.setDateHeader("Expires", 0);
Enumeration enum = req.getHeaderNames();
while (enum.hasMoreElements()) {
��String headerName = (String) enum.nextElement();
��String headerVal = req.getHeader(headerName);
��out.println(headerName + " : " + headerVal + "<BR>");
}
...  

To view the HTTP headers for your requests and responses, you can use the TCPMonitor utility. For more information, see "Using TCPMonitor".

To see a sample servlet, start the samples JRun server and open a browser to http://localhost:8200/techniques.

Using the PrintWriter

The PrintWriter writes character data to the response object. It includes print and println methods. The PrintWriter requires that you import the java.io.* package and catch IOExceptions.

The following example shows how to use the PrintWriter's out method in a servlet to print a response back to the requesting client:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class PrintTester extends HttpServlet {
��public void doGet ( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
��PrintWriter out = response.getWriter();
��out.println("<html><head><title>PrintTester</title></head>");
��out.println("<body>Hello from PrintTester");
��out.println( "</body></html>");
��}
}

To see a sample servlet, start the samples JRun server and open a browser to http://localhost:8200/techniques.

Using the ServletOutputStream

The ServletOutputStream object writes binary data back to the client. It includes print and println methods. Since it is a subclass of java.io.OutputStream, it also has flush, close, and write methods. The ServletOutputStream requires that you import the java.io.* package and catch IOException.

The following example uses the ServletOutputStream's methods in a servlet to print a response back to the requesting client:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SOSTester extends HttpServlet {
public void doGet ( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
��ServletOutputStream sos = response.getOutputStream();
��String s = "hello from SOSTester";
��sos.print(s);
��sos.close();
��}
}

To see a sample servlet, start the samples JRun server and open a browser to http://localhost:8200/techniques.

 

Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/jrun/4/Programmers_Guide/techniques_servlet10.htm