drno-reg
@drno-reg
см не кратко

Почему сервлет — фильтр аутентификации на форме ввода имени и пароля срезает CSS, JS, картинки и т.д.?

Здравствуйте.

Пытаюсь допилить сервлет - фильтр аутентификации.
Сразу скажу использовал идею с

Получилось где-то так

public class AuthenticationFilter implements Filter {

    private ServletContext context;

    public void init(FilterConfig fConfig) throws ServletException {
        this.context = fConfig.getServletContext();
        this.context.log("AuthenticationFilter initialized");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        String uri = req.getRequestURI();
        this.context.log("Requested Resource::" + uri);

        HttpSession session = req.getSession(false);
        Object user_o = req.getSession().getAttribute("username");
        this.context.log("Фильтр аутентификации, пользователь::" + user_o);

        if (user_o == null && !(uri.endsWith("index.jsp") || uri.endsWith("LoginUser"))) {
            this.context.log("Неавторизованный запрос");
            res.sendRedirect("index.jsp");

        } else {
            // pass the request along the filter chain
            this.context.log("Авторизованный запрос, сессия:: " + session);
            chain.doFilter(request, response);
        }
        
    }

    public void destroy() {
        //close any resources here
    }
}


Проблема в том, что когда открывается форма валидации пользователя index.jsp - на ней не работает ни CSS, ни JS, не отображаются картинки.
Сервлет валидации логина - LoginUser
В чем может быть проблема?

С отключенным фмльтром отображается все нормально.
  • Вопрос задан
  • 567 просмотров
Решения вопроса 1
drno-reg
@drno-reg Автор вопроса
см не кратко
Проблему удалось решить так

@WebServlet(
        name = "AuthenticationFilter",
        description = "Аутентификационный фильтр",
        urlPatterns = "/AuthenticationFilter"
)
@WebFilter("*.jsp")
public class AuthenticationFilter implements Filter {

    private ServletContext context;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.context = filterConfig.getServletContext();
        this.context.log("AuthenticationFilter initialized");
    }

    @Override
    public void destroy() {
        //close any resources here
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        String uri = req.getRequestURI();
        this.context.log("Requested Resource::" + uri);

        HttpSession session = req.getSession(false);
        Object user_o = req.getSession().getAttribute("username");
        this.context.log("Фильтр аутентификации, пользователь::" + user_o);

        if (user_o == null && !(uri.endsWith("index.jsp") || uri.endsWith("LoginUser"))) {
            this.context.log("Неавторизованный запрос");
            res.sendRedirect("index.jsp");

        } else {
            // pass the request along the filter chain
            this.context.log("Авторизованный запрос, сессия:: " + session);
            chain.doFilter(request, response);
        }
        
    }

    }
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
jaxtr
@jaxtr
JavaEE/Spring-разработчик
А на какой путь вешается фильтр? И какие пути у статических ресурсов? Скорее всего пути статических ресурсов попадают под действие фильтра, который редиректит запросы на index.jsp.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы