Response Generation

A request generally warrants a response, and servlets are no exception in this regard.

Servlets make use of ServletResponse to simplify this common task. The ServletResponse object, commonly referred to as the response object, is in fact provided to a servlet alongside the request object as a parameter to the service method.

Output can be written in either binary or character format by obtaining a handle to either a ServletOutputStream object or a PrintWriter object, respectively. Some of the other methods provided by the ServletResponse interface are contained in the following list:

  • getOutputStream obtains the handle to a ServletOutputStream object for binary data.

  • getWriter obtains the handle to a PrintWriter object for character data.

  • setBufferSize can be used to establish the buffer size for the response to enable better performance tuning.

  • flushBuffer flushes the current contents of the buffer.

For more information, see javax.servlet.ResponseObject and javax.servlet. ServletOutputStream.

An HTTP specific response object is also available and provides additional capabilities related to HTTP response header formulation. See javax.servlet. http.HttpServletResponse for more information.

Figure 10-4 shows a simple usage scenario involving a response object.

Figure 10-4. Generating the response
PrintWriter out;
:
// set content type
response.setContentType("text/html");
:
out = response.getWriter();
out.println("<HTML><HEAD><TITLE>");
:
out.println("Login Unsuccessful");
:
out.flush();
out.close();

Alternatives for Response Generation

If you take a good look at Figure 10-4, you will see several HTML tags involved in the generation of output from the servlet. This represents only one approach for generation of dynamic output.

Another similar but more structured approach is to use libraries of HTML files to generate common headers and footers for the necessary response Web pages, with the dynamic portion of the page still generated much like what was shown in Figure 10-4.

A third and cleaner approach is to use the power of JSP and JavaBeans whenever possible. In this approach, the servlet simply needs to forward to a JSP page that contains all of the necessary presentation information and use JSP technology and JavaBeans to fill in the dynamic content portions of the page. Other than the forward, the servlet has little else to do with presentation except perhaps coordinating the necessary items for the JSP page to successfully do its work.

We discuss this approach further in Chapter 11.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.186.83