First let's clear some vocabulary:
Back to your question. When using RequestDispatcher
by calling ServletContext.getRequestDispatcher(String)
you must always forward within your web application and leading slash is necessary (bold mine):
The pathname must begin with a /
and is interpreted as relative to the current context root.
So when you forward to /page01.jsp
it is interpreted as: /your_context/page01.jsp
where your_context
is the name of your web application.
However when you send redirect to the /error.jsp
path, servlet container simply sends that address back in 302 response to the browser. Now the browser interprets it as follows: please redirect to /error.jsp
, an absolute path in the current server. So even if the browser was pointing to http://example.com/foo/bar/servlet
, this response redirects to http://example.com/error.jsp
.
It's much different, however, if you simply redirect to error.jsp
the browser behaves differently. It interprets it as file in current directory. So http://example.com/foo/bar/servlet
will be redirected to http://example.com/foo/bar/error.jsp
. And this is what you see.