2

when i try to redirect my servlet to error page "error.jsp" using response.sendRedirect("/error.jsp") it shows page not found error but when i change it to response.sendRedirect("error.jsp"), it works fine!

why is it so? why is relative path not working? error.jsp is saved in WEB-CONTENT folder. The dispatcher.foreward(request,response), works fine with relative url "/page01.jsp", even though both page01.jsp and error.jsp are in same directory WEB-CONTENT. please explain.

thanks!

4

4 回答 4

8

First let's clear some vocabulary:

  • error.jsp and ./../error.jsp are examples of relative paths

  • /page01.jsp and /app/page.html are examples of absolute paths

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.

于 2013-01-12T10:02:51.507 回答
1

If you pass a String starting with '/' to HttpServletResponse#sendRedirect the path will be relative to the server and not your application. So, you should pass something like this to get this working:

response.sendRedirect("/myapp/error.jsp");

于 2013-01-12T09:54:34.253 回答
0

try the servlet mapping in web.xml , instead of calling file using name, just call using value, defined in web.xml.

于 2013-01-12T10:04:48.303 回答
0

please remeber some points while using sendRedirect() and getRequestDispacher() in the same page

1) if you use sendRedirect() and getRequestDispacher("").include() in same page always the output of sendRedirect() that is calling url will be printed on UI.

2) 1) if you use sendRedirect() and getRequestDispacher("").forward(req,res) in same page then you will get Excetion "Cannot forward after response has been committed".

于 2015-07-09T11:07:54.203 回答