Java过滤器用于重定向未登录到登录页面的用户 [英] Java Filter to redirect users who are not logged in to login page
问题描述
我试图制作一个过滤器来阻止未登录的用户访问某些页面。为此,我使用以下 doFilter
方法制作了一个过滤器类
I was trying to make a filter to stop users who are not logged in from accessing certain pages.For this i made a filter class with the following doFilter
method
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String url = request.getRequestURI();
boolean allowedRequest = false;
System.out.println(url);
if(urlList.contains(url)) {
allowedRequest = true;
System.out.println("in list");
}
if (!allowedRequest) {
Object o = request.getSession().getAttribute("UserInfo");
if (null == o) {
System.out.println("Hey i am in");
response.sendRedirect("/login.jsp");
}
}
chain.doFilter(req, res);
} // end of doFilter
允许不需要的页面要登录的用户我在init()中创建了一个arraylist url-list
To allow the pages which doesnot need the user to be logged in i created an arraylist url-list in init()
现在发生了一个非常奇怪的愚蠢事情。假设我有两页home.jsp和dcr.jsp。当我尝试访问home.jsp而没有登录时,我成功地重定向到login.jsp,但是当我试图访问dcr.jsp时它没有重定向,虽然它进入循环如果(null == o)我能理解因为我在控制台中打印该行.TH是我在服务器中获得的输出
这是我在服务器中获得的输出
Now a very strange stupid thing is happening. suppose i have two pages home.jsp and dcr.jsp. When i try to access home.jsp without logging in the i am successfully redirected to login.jsp but when i am trying to access dcr.jsp it is not redirected although it enters the loop if(null == o) which i can understand because i am getting that line printed in console.THis is the output that i get in the server This is the output that i get in the server
/dcrmaintenance.jsp
Hey i am in
这告诉我null == o是真的。
Which tells me that the null == o was true.
页面dcr.jsp访问会话对象,因为用户没有登录,所以它正在获取java.lang.NullPointerException如预期的那样,但我无法理解为什么即使进入循环后重定向也没有发生。如果有人可以说出我犯了错误的地方,我们将不胜感激。
The page dcr.jsp accesses a session object and since the user is not logged in it is getting java.lang.NullPointerException as expected but i cannot understand why is the redirection not taking place even after entering the loop.If someone can pt out where i am making a mistake it would be appreciated.
推荐答案
在之后,response.sendRedirect(/ login.jsp);
执行返回;
。
这篇关于Java过滤器用于重定向未登录到登录页面的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!