Я использую сервлет jsp для создания веб-приложения, я хочу запретить пользователю показывать страницу входа, если он уже вошел в систему, я делаю фильтр, который проверяет это, но он по-прежнему показывает страницу входа, даже если у пользователя есть действительный сессия, Вот код в фильтре.
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:
Вот отображение URL в файле web.xml
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/Admin/*</url-pattern>
</filter-mapping>
, поскольку Admin - это папка, расположенная вне папки WEB-INF.