I have a problem with redirection – it simply does not work for valid paths.
Right now I use page forwarding in the Servlet, but I need redirection in a filter.
All the pages reside in the ‘pages’ folder and have a .jspx extension
I’ve tried the following (this path works with forwarding):
httpResponse.sendRedirect("/pages/login.jspx");
browser url is http://[localhost]/pages/login.jspx, and it shows Tomcat’s 404 page, the context path (in my case it’s ‘/hotel’) is missing from the url, so, if I add it:
httpResponse.sendRedirect("/hotel/pages/login.jspx");
redirect does not happen, browser url does not change, and I’m shown the browser’s 404 page (This program cannot display the webpage).
What am I doing wrong?
The filter which is used to test this has the following mapping:
@WebFilter(filterName = "SecurityFilter", urlPatterns = "/*")
The redirected URL is indeed relative to the initially requested URL. To dynamically prepend the context path it’s recommended to use
HttpServletRequest#getContextPath()instead of hardcoding it, because the context path value can be changed externally by server-specific configuration.As to your concrete problem, I’m not sure if I understand “browser’s 404 page” properly, perhaps you mean the browser-default error page which can occur when the server is unreachable or when the request has been redirected in an infinite loop (that should however have been made clear in the actual message of the browser default error page, at least Chrome and Firefox do that).
Given that your filter is mapped on
/*, it’s actually redirecting in an infinite loop because the request URL of the login page in turn also matches the URL pattern of the filter.You’d need either to put the filter on a more specific URL pattern which does not cover the login page, e.g. on
/secured/*where all restricted pages are been moved in there (or map it on/pages/*and put the login page outside there), or to fix your filter as follows: