我有一个身份验证过滤器,可以阻止用户浏览到您需要登录的任何页面:
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 be.kdg.repaircafe.beans.UserBean@350af1bb
Info: username is null
Info: request url is /javax.faces.resource/repaircafe_logo.png.xhtml
Info: user is be.kdg.repaircafe.beans.UserBean@350af1bb
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(),为什么他仍然转发我而不是索引?
答案 0 :(得分:0)
我通过查看另一个stackoverflow答案来解决这个问题,如果我只是在重定向后点击返回它会阻止过滤器进行前进。