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:
But if the argument to sendRedirect() DOES start with a forward slash:
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:
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...)
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”));