Servlet redirect makes the browser do the work

A redirect lets the servlet off the hook completely. After deciding that it can’t do the work, the servlet simply calls the sendRedirect() method:

image with no caption

Using relative URLs in sendRedirect()

You can use a relative URL as the argument to sendRedirect(), instead of specifying the whole “http://www...” thing. Relative URLs come in two flavors: with or without a starting forward slash (“/”).

Imagine the client originally typed in:

image with no caption

But if the argument to sendRedirect() DOES start with a forward slash:

image with no caption

The Container builds the complete URL relative to the web Container itself, instead of relative to the original URL of the request. So the new URL will be:

image with no caption

Watch it!

You can’t do a sendRedirect() after writing to the response!

That’s probably obvious, but it’s the LAW so we’re just making sure.

If you look up sendRedirect() in the API, you’ll see that it throws an IllegalStateException if you try to invoke it after “the response has already been committed.”

By “committed”, they mean that the response has been sent. That just means the data has been flushed to the stream.

For practical purposes, it means you can’t write to the response and then call sendRedirect()!

But some picky professor will tell you that technically, you could write to the stream without flushing, and then sendRedirect() wouldn’t cause an exception. But it would be a completely stupid thing to do, so we won’t talk about it. (Except that we just did... talk about it...)

In your servlet, for gosh sakes make a decision! Either handle the request or do a sendRedirect() to have someone ELSE handle the request.

(By the way, this idea that “once it’s committed it’s too late” also applies to setting headers, cookies, status codes, the content-type, and so on...)

Note

sendRedirect() takes a String, NOT a URL object!

Well, it takes a String that IS a URL. The point is, sendRedirect() does NOT take an object of type URL. You pass it a String that’s either a complete URL or a relative one. If the Container can’t build a relative URL into a full one, it’ll throw an IllegalStateException. The tricky part is to remember that THIS is wrong: sendRedirect(new URL(“www.oreilly.com”));

Note

No! It looks so right, but it’s SO wrong. sendRedirect() takes a String. Period.

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.