Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
168
Chapter 7 Generating the Server Response: HTTP Response Headers
7.5 Using Servlets to Generate GIF
Images
Although servlets often generate HTML output, they certainly don't always
do so. For example, Section 11.2 (The contentType Attribute) shows a JSP
page (which gets translated into a servlet) that builds Excel spreadsheets and
returns them to the client. Here, I'll show you how to generate GIF images.
First, let me summarize the two main steps servlets have to perform in
order to build multimedia content. First, they have to set the
Content Type
response header by using the
setContentType
method of
HttpServlet
Response
. Second, they have to send the output in the appropriate format.
This format varies among document types, of course, but in most cases you
use send binary data, not strings as with HTML documents. Consequently,
servlets will usually get the raw output stream by using the
getOutput
Stream
method, rather than getting a
PrintWriter
by using
getWriter
.
Putting these two points together, servlets that generate non HTML content
usually have a section of their
doGet
or
doPost
method that looks like this:
response.setContentType("type/subtype");
OutputStream out = response.getOutputStream();
Those are the two general steps required to build non HTML content.
Next, let's look at the specific steps required to generate GIF images.
1. Create an
Image
.
You create an
Image
object by using the
createImage
method
of the
Component
class. Since server side programs should not
actually open any windows on the screen, they need to explicitly
tell the system to create a native window system object, a pro
cess that normally occurs automatically when a window pops
up. The
addNotify
method accomplishes this task. Putting this
all together, here is the normal process:
Frame f = new Frame();
f.addNotify();
int width = ...;
int height = ...;
Image img = f.createImage(width, height);
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved