我是Servlet和Filter的新手。我试图阻止所有未在我的应用程序中登录的用户。
Web.xml文件
<filter>
<filter-name>UserFilter</filter-name>
<filter-class>user.UserFilter</filter-class>
<init-param>
<param-name>avoid-urls</param-name>
<param-value>index.jsp, SelectDb.jsp, login.jsp</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>UserFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
过滤类
package user;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class UserFilter implements Filter {
private ArrayList<String> urlList;
public UserFilter() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String url = request.getServletPath();
String contextPath = request.getContextPath();
boolean allowedRequest = false;
for (String urlList1 : urlList) {
if (url.contains(urlList1)) {
allowedRequest = true;
break;
}
}
if (!allowedRequest) {
HttpSession session = request.getSession();
if (null == session) {
response.sendRedirect("");
} else {
String logged = (String) session.getAttribute("username");
if (logged == null) {
response.sendRedirect(request.getContextPath() + "/dashboard/SelectDb.jsp");
} else {
chain.doFilter(request, response);
}
}
} else {
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig config) {
String urls = config.getInitParameter("avoid-urls");
StringTokenizer token = new StringTokenizer(urls, ",");
urlList = new ArrayList<>();
while (token.hasMoreTokens()) {
urlList.add(token.nextToken());
}
}
}
我可以看到页面正确地重定向到我想要重定向的页面。网址正在发生变化。但Firefox
表示页面未正确重定向。消息有点像这样:Firefox has detected that the server is redirecting the request for this address in a way that will never complete. This problem can sometimes be caused by disabling or refusing to accept cookies
。我不认为这个错误来自浏览器本身。因为我也尝试过其他浏览器。为什么这个错误?如何解决这个错误?
答案 0 :(得分:0)
尝试替换
HttpSession session = request.getSession();
到
HttpSession session = request.getSession(false);
如果还没有会话, request.getSession()
将创建一个新会话,因此它永远不会返回null,因此用户被重定向到他有!allowedRequest
的selectDb url并且它进入和无限重定向