I have a filter that provides user authorization, but the problem is that it violates the single responsibility principle, it goes to the database to check if the user exists, and checks the session for the presence of such a user. And I want to divide this filter into two. But the problem is that I need to make these 2 checks in one branch of conditional operators, respectively, it is necessary to transfer data. How can I do that?

@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { final HttpServletRequest req = (HttpServletRequest) request; final HttpServletResponse res = (HttpServletResponse) response; final HttpSession session = req.getSession(false); if (nonNull(session) && sessionContainKey(session)) { req.getRequestDispatcher("/WEB-INF/views/index.jsp") .forward(req, res); filterChain.doFilter(request, response); } else if (userExistInDB(req, getDBExecutor(req))) { //Инструкции этого ветвления я хочу перенести в другой фильтр вместе с userExistInDB за которым стоит коннект с базой. setSessionAttribute(req.getSession(), req.getParameter("name")); req.getRequestDispatcher("/WEB-INF/views/index.jsp") .forward(req, res); filterChain.doFilter(request, response); } else { req.getRequestDispatcher("/WEB-INF/views/login.jsp") .forward(req, res); } } 
  • Ahaha, good luck keeping SOLID - Alex78191

1 answer 1

 if (session != null && session.getAttribute("name") != null) { // Сессия уже открыта. Продолжить нормальную обработку filterChain.doFilter(); } else { if (req.getParameter("name") == null) { // Нет ни сессии ни запроса авторизации. Показать страницу login req.getRequestDispather("/WEB-INF/views/login.jsp").forward(...); } else { if (!userExistsInDb(...)) { // Неудачная попытка авторизации. Показать страницу login req.getRequestDispather("/WEB-INF/views/login.jsp").forward(...); } else { // Удачная авторизация. Создать сессию и продолжить нормальную обработку req.getSession().setAttribute("name", ...); filterChain.doFilter(); } } } 

And you can transfer data between filters. For example, in one filter to put an object in request, in another, respectively, to extract

The first

 req.setAttribute("Юстас-Алексу", "Штирлец шел по лесу и напоролся на сук. Суки разбежались с визгом. Визг бежал первым."); 

Second

 String fromUstas = req.getAttribute("Юстас-Алексу");