O'Reilly logo

Head First Servlets and JSP, 2nd Edition by Bert Bates, Bryan Basham, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Whoa. What’s the deal with content type?

You might be wondering about this line:

response.setContentType("application/jar");

Or at least you should be. You have to tell the browser what you’re sending back, so the browser can do the right thing: launch a “helper” app like a PDF viewer or video player, render the HTML, save the bytes of the response as a downloaded file, etc. And since you’re wondering, yes when we say content type we mean the same thing as MIME type. Content type is an HTTP header that must be included in the HTTP response.

image with no caption

Common MIME types:

text/html

application/pdf

video/quicktime

application/java

image/jpeg

application/jar

application/octet-stream

application/x-zip

Relax

You don’t need to memorize a bunch of content types.

You should know what setContentType() does, and how you use it, but you don’t have to know even the most common content types except text/html What you need to know about setContentType() is mostly common sense... for example, it won’t do you any good to change the content type AFTER you write to the response output stream. Duh. But that does mean that you can’t set a content type, write some stuff, and then change the content type and write something different. But think about it—how would the browser deal with that? It can handle only one type of THING at a time from the response.

To make sure everything works correctly, your best practice (and in some cases a requirement) is to always call setContentType() first, BEFORE you call the method that gives you your output stream (getWriter() or getOutputStream()). That’ll guarantee you won’t run into conflicts between the content type and the output stream.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required