我有一個是應該從瀏覽到您需要先登錄任何網頁停止用戶的身份驗證篩選:Servlet過濾混亂,響應重定向沒有發生
public class AuthenticationFilter implements Filter {
private FilterConfig fc;
private final String indexURL = "/index.xhtml";
private final String registerUrl = "/register/register.xhtml";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.fc = filterConfig;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
HttpSession session = req.getSession();
UserBean user = (UserBean) session.getAttribute("userBean");
String requestUrl = req.getRequestURI();
System.out.println("user is " + user);
if (user != null) {
System.out.println("username is " + user.getUsername());
if (user.getUsername() == null || user.getUsername().equalsIgnoreCase("")) {
System.out.println("request url is " + requestUrl);
if (!requestUrl.equalsIgnoreCase(indexURL) &&
!requestUrl.equalsIgnoreCase(registerUrl) && !requestUrl.startsWith("/javax.faces.resource")) {
//Redirect back to indexpage
System.out.println("request url is not for index/register/resource, it is: " + requestUrl);
resp.sendRedirect(indexURL);
};
}
} else {
resp.sendRedirect(indexURL);
}
chain.doFilter(req, resp);
}
@Override
public void destroy() {
}
}
它實際上是打印什麼,我期待,但它沒有做重定向,這是(最後一部分)我的日誌信息:編輯
Info: request url is /javax.faces.resource/jquery/jquery.js.xhtml
Info: user is [email protected]
Info: username is null
Info: request url is /javax.faces.resource/repaircafe_logo.png.xhtml
Info: user is [email protected]
Info: username is null
Info: request url is /welcome.xhtml
Info: request url is not for index/register/resource, it is: /welcome.xhtml
Severe: Error Rendering View[/welcome.xhtml] --> I just told you to redirect! Why are you doing this to me??
:一些調試後,我發現,調試器到達的chain.doFilter()後,他甚至重定向迴應,爲什麼他仍然轉發我歡迎而不是索引?
是調試指針被擊中'resp.sendRedirect(indexURL); '? – Amogh
如果'requestUrl'和'indexURL'是相同的,我不認爲它會進入內部if。 – Amogh
如果你重定向,你不應該調用chain.doFilter(req,resp);之後。 –