防止用户登录后返回登录页面jsp servlet
问题描述:
我正在使用jsp servlet创建一个web应用程序,我想阻止用户显示登录页面,如果他已经登录,我做一个过滤器来检查,但它仍然显示登录页面,即使用户有一个有效的会话,以下是过滤器中的代码。防止用户登录后返回登录页面jsp servlet
HttpSession session = httpreq.getSession(false);
if(session == null){
System.out.println("not logged, redirect ");
httpres.sendRedirect("../Login.jsp");
}
else{
System.out.println("could be logged");
String logged = (String) session.getAttribute("Login");
if(logged != null){
System.out.println(" logged "+logged);
if (!logged.equals("ok")) { // user is not logged
System.out.println("not logged, redirect ");
httpres.sendRedirect("../Login.jsp");
return;
} else { // if user has a session redirect his to the page he was opened
System.out.println("redirect to the same page");
chain.doFilter(request, response);
System.out.println("redirect to the same page");
httpres.setCharacterEncoding("UTF-8");
httpres.sendRedirect(httpreq.getRequestURI());
}
}else
{
System.out.println("not logged, redirect login ");
httpres.sendRedirect("../Login.jsp");
return;
}
}
我只对位于WEB-INF文件夹外的文件夹进行会话。
编辑:下面的代码来检查用户的有效性和属性添加到会话
isVaild = StudentManagement.isValidUser(connection, studentUserName, password);
// I have more than one roles in the system..
}
if (isVaild) {
System.out.println("create session");
HttpSession session = request.getSession();
session.setAttribute("Login", "ok");
session.setAttribute("userName", userName);
session.setAttribute("role", role);
if (role == UserRole.STUDENT) { //student role
url = "/ParentManagementServlet?pageName=StudentActivationPage";
forward(request, response, url);
} else if (role == UserRole.ADMIN) { //admin role
url = "/Admin/MainPage.jsp";
forward(request, response, url);
}
编辑2: 这里是在web.xml文件中的URL映射
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/Admin/*</url-pattern>
</filter-mapping>
,因为Admin是位于WEB-INF文件夹之外的文件夹。
答
似乎一切都很好,除了过滤器映射,尝试 -
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/protected directory/*</url-pattern>
</filter-mapping>
我假设你想要保护的目录,上面的URL模式将检查整个目录的一切..你可以罚款根据需要调整模式。
但问题是 - 有问题(<url-pattern>/Admin/*</url-pattern>
)提到的模式确实不拦截Login.jsp
,这就是为什么它不能执行会话确认并呈现Login.jsp
甚至对有效会话。
您可以在现有的过滤器中执行检查 - 请求是否适用于Login.jsp,然后可以做出决定(我不知道这是否是一种好的方法)否则将Login.jsp保留在并编写另一个只匹配的过滤器Login.jsp
你在哪写过这个逻辑? – 2011-04-24 17:13:31
在servlet过滤器中。 – palAlaa 2011-04-24 17:19:12
@Alaa - 你能解释一下吗 - 当用户可以看到登录页面时? 1)通过再次点击登录页面URL或2)使用浏览器的后退按钮 – Premraj 2011-04-24 17:20:43