Servlet filter prevents css from working

无人久伴 提交于 2020-12-08 02:19:24

问题


I'm working on a java project based on spring-MVC. I have users - students in this issue - which I'd like to check on each page they navigate, if they are logged it. So I wrote a web filter, that runs before each page loading and assures that user is logged in and is a student- except for login page ( obviously user is not logged in there :D) and home page which is reachable for everyone- however, when I added this filter to the project, all css got disabled, all images disappeared, and I suppose if I had any js that would get disabled too(That is just a guess, but I believe the page's access to Resource folder is somehow banned. Since I referred to it with this pattern:

${pageContext.request.contextPath}/resources

Here is my filter's doFilter method, is there anything I'm getting wrong here?

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    HttpSession session = request.getSession(false);
    String loginURI = request.getContextPath() + "/studentLogin"; /* student login page */
    String mainPage = request.getContextPath() + "/"; /* ?! */

    boolean loggedIn = (session != null) && (session.getAttribute("type") != null) && (session.getAttribute("type") == "s");
    boolean loginRequest = request.getRequestURI().equals(loginURI);
    boolean isMainPage = request.getRequestURI().equals(mainPage);

    if (loggedIn || loginRequest||isMainPage) { //if: user is logged in, or user is attempting to login, or user is just looking at the main page and has nothing to do with us
        chain.doFilter(request, response);//let it go :d
    } else {
        response.sendRedirect(loginURI); //redirect user to login page!! this user mustn't be here!
    }
}

Any advice would be greatly appreciated.


回答1:


You need to allow for your filter to bypass static resources, something like this:

boolean isStaticResource = request.getRequestURI().startsWith("/resources/");

if (loggedIn || loginRequest || isMainPage || isStaticResource) { 
    chain.doFilter(request, response);
} else {
    response.sendRedirect(loginURI);
}


来源:https://stackoverflow.com/questions/44702494/servlet-filter-prevents-css-from-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!