拦截器 Filter : js、css、jpg、png等静态资源不被拦截解决方案

方案一:

web.xml配置文件拦截范围缩小 ,没有必要 /*的配置拦截项目下所有资源。

<filter>
        <filter-name>Login</filter-name>
        <filter-class>com.ssm.crm.filter.LoginFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Login</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

修改如下:

    <filter>
        <filter-name>Login</filter-name>
        <filter-class>com.ssm.crm.filter.LoginFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Login</filter-name>
        <url-pattern>*.action</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>Login</filter-name>
        <url-pattern>*.do</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>Login</filter-name>
        <url-pattern>*.jsp</url-pattern>
    </filter-mapping>

进一步优化 :把所有的页面无需拦截的文件(jsp,html,ftl,css等放在同一个文件夹下;需要拦截的请求公有路径也统一)拦截是配置为:

<filter-mapping>
        <filter-name>Login</filter-name>
        <url-pattern>/文件夹名字/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>Login</filter-name>
        <url-pattern>/需要拦截的请求公有路径/*</url-pattern>
    </filter-mapping>

方案二:

过滤掉js,css等相关文件

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse res = (HttpServletResponse)response;
        HttpSession session = req.getSession();
        LoginUser loginUser = (LoginUser) session.getAttribute("loginUser");
        String spath = req.getServletPath();
    System.out.println("request.getContextPath()"+req.getContextPath());
        //不需要过滤的url
        String[] urls = {"/login","/json",".js",".css",".ico",".jpg",".png"};
        boolean flag = true;
        for (String str : urls) {
            if (spath.indexOf(str) != -1) {
                flag =false;
                break;
            }
        }
        if (flag) {
            if (loginUser != null) {
                chain.doFilter(request, response);
            }else {
                res.sendRedirect(req.getContextPath()+"/webpage/page/login/login.jsp");
            }
        }else{
            chain.doFilter(request, response);  
       }

    }

 

posted @ 2020-02-28 16:03  henrypaul  阅读(4904)  评论(0编辑  收藏  举报