我想实现一个过滤器来进行身份验证,但不知何故它陷入了无限循环……任何想法都很感谢。
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
doBeforeProcessing(request, response);
Throwable problem = null;
HttpSession session = httpRequest.getSession(true);
if(session.getAttribute("userName")!=null&&session.getAttribute("userName")!=(""))
{
try {
chain.doFilter(request, response);
} catch (Throwable t) {
// If an exception is thrown somewhere down the filter chain,
// we still want to execute our after processing, and then
// rethrow the problem after that.
problem = t;
t.printStackTrace();
}
}else{
httpResponse.sendRedirect("login.jsp");
return;
}这段代码在调试模式下运行了无限次,基本上我想在用户未登录时将其重定向到login.jsp。任何回答都很感谢。
发布于 2012-10-29 09:22:39
这里,
httpResponse.sendRedirect("login.jsp");您将为目标页面发送一个新的HTTP请求,而不是使用当前的请求。如果这个新的超文本传输协议请求被映射到一个过于通用的URL模式,比如/*,那么它当然会再次命中过滤器。并且将执行相同的检查并且它将再次被重定向。等等。这是一个永无止境的故事。
当当前请求的页面是登录页面时,还需要添加额外的检查来执行FilterChain#doFilter()。
String loginURL = httpRequest.getContextPath() + "/login.jsp";
if (httpRequest.getRequestURI().equals(loginURL)) || session.getAttribute("userName") != null) {
chain.doFilter(request, response);
} else {
httpResponse.sendRedirect(loginURL);
}注意,我还删除了对作为username的空字符串的无意义的检查(但是,您需要确保您的代码没有将空字符串设置为username。只需使用null表示未登录的用户即可。还请注意,我还修复了重定向URL,因为当当前请求的URL在子文件夹中时,它将失败。
一种不同的选择是将所有这些受限制的页面放在一个公共的子文件夹中,例如/app、/secured、/restricted等,然后将过滤器映射到/app/*、/secured/*、/restricted/*等的URL模式。如果您将登录页面放在此文件夹之外,则在请求登录页面时不会调用筛选器。
发布于 2012-10-29 09:23:21
问题是您的筛选器是在login.jsp上运行的,当用户未登录时,将反复重定向到它自己。由于filter url-pattern上没有排除语法,因此如果您已经在login.jsp页面上,则需要检测过滤器中的URL并省略重定向:
// your auth code
} else {
String redirect = httpRequest.getContextPath() + "/login.jsp";
String uri = httpRequest.getRequestURI().toString();
if (uri.endsWith(redirect)){
// URI ends with login.jsp, just process the chain
chain.doFilter();
} else {
// not on the login page and not logged in, redirect
httpResponse.sendRedirect(redirect);
return;
}
}https://stackoverflow.com/questions/13114743
复制相似问题