重定向的 URL 确实与最初请求的 URL 相关。要动态添加上下文路径,建议使用HttpServletRequest#getContextPath()
而不是硬编码它,因为上下文路径值可以通过特定于服务器的配置在外部进行更改。
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:
String loginURL = request.getContextPath() + "/pages/login.jspx";
if (needsToRedirect && !request.getRequestURI().equals(loginURL)) {
response.sendRedirect(loginURL);
}
else {
chain.doFilter(request, response);
}