Servlet过滤器可防止css工作

时间:2017-06-22 14:36:21

标签: java spring-mvc servlet-filters

我正在开发基于spring-MVC的java项目。我有用户 - 这个问题的学生 - 我想要检查他们浏览的每个页面,如果他们已经登录了。所以我写了一个web过滤器,它在每个页面加载之前运行,并确保用户已登录并且是学生 - 除了登录页面(显然用户没有登录到那里:D)和主页,每个人都可以访问 - 但是当我将这个过滤器添加到项目中时,所有css都被禁用,所有图像都消失了,我想如果我有任何js也会被禁用(这只是猜测,但我相信页面的访问权限)资源文件夹以某种方式被禁止。因为我用这种模式引用它:

${pageContext.request.contextPath}/resources

以下是我的过滤器doFilter方法,我在这里遇到了什么问题吗?

@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!
    }
}

非常感谢任何建议。

1 个答案:

答案 0 :(得分:0)

您需要允许过滤器绕过静态资源,如下所示:

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

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