Servlet Filter 过滤器 对指定页面不拦截

2018/03/06 14:47
阅读数 0
package niit.dxs.controller;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    private String excludedPage;
    private String[] excludedPages;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        excludedPage = filterConfig.getInitParameter("excludedPages");
        if (excludedPage != null && excludedPage.length() > 0){
            excludedPages = excludedPage.split(",");
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取 resquest、response、session
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();

        // 定义表示变量 并验证用户请求URL 是否包含不过滤路径
        boolean flag = false;
        for (String page:excludedPages) {
            if (request.getServletPath().equals(page)){
                flag = true;
            }
        }

        // 验证用户登录
        if (flag){
            filterChain.doFilter(request,response);
        }{
            String userName= (String) session.getAttribute("userKey");
            System.out.println("userid——————————》"+userName);
            if (userName != null){
                filterChain.doFilter(request,response);
            }else {
                request.getRequestDispatcher("index.jsp").forward(request,response);
            }
        }
    }

    @Override
    public void destroy() {

    }
}

 

 

web.xml

 

 

<!--  过滤器   -->
<filter>
    <filter-name>LoginFilter</filter-name>
    <filter-class>niit.dxs.controller.LoginFilter</filter-class>
    <init-param>
        <param-name>excludedPages</param-name>
        <param-value>/index.jsp,/register.html,/RegisterServlet,/LoginServlet</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部