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

You can set response headers, you can add response headers

And you can wonder what the difference is. But think about it for a second, then do this exercise.

Match the method call with its behavior

Draw a line from the HttpResponse method to the method’s behavior. We did the most obvious one for you.

Pretty obvious when you see them all together.

But for the exam, you should have them memorized so that if next Tuesday the guy down the hall asks, “What’s that response method that lets me add a value to an existing header?” you can, without the slightest pause, say “It’s addHeader, and it takes two Strings for the name and value.” Just like that.

Both setHeader() and addHeader() will add a header and value to the response if the header (the first argument to the method)is not already in the response. The difference between set and add shows up when the header is there. In that case:

setHeader() overwrites the existing value

addHeader() adds an additional value

When you call setContentType(“text/html”), you’re setting a header just as if you said:

setHeader(“content-type”, “text/html”);

So what’s the difference? No difference... assuming you type the “content-type” header correctly. The setHeader() method won’t complain if you misspell the header names—it just thinks you’re adding a new kind of header. But something else will fail later, because now you haven’t properly set the content type of the response!

Note

(The first person to send us an mp3 file of them actually reciting this poem, with the right timing and everything, gets a special edition t-shirt.)

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