我想实现一个过滤器来进行身份验证,但不知何故它陷入了无限循环......任何想法表示赞赏。
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。
任何答案表示赞赏。
Here,
httpResponse.sendRedirect("login.jsp");
你正在发送一个new对目标页面的 HTTP 请求,而不是使用当前请求。如果这个新的 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);
}
请注意,我还删除了对空字符串作为用户名的无意义检查(但是您要确保your代码没有将空字符串设置为用户名。只需使用null
代表未登录的用户。另请注意,我还修复了重定向 URL,因为当当前请求的 URL 位于子文件夹中时,它会失败。
另一种替代方法是将所有这些受限制的页面放在一个公共子文件夹中,例如/app
, /secured
, /restricted
等,然后将过滤器映射到 URL 模式/app/*
, /secured/*
, /restricted/*
等代替。如果您将登录页面保留在此文件夹之外,则在请求登录页面时将不会调用过滤器。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)