zoukankan      html  css  js  c++  java
  • Servlet Filter 过滤器 对指定页面不拦截

    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>
  • 相关阅读:
    SQL必知必会-笔记(五)函数
    软件测试面试题:系统中的图片不显示如何排查原因
    windows用浏览器访问linux目录文件
    记测试工作中一次印象深刻的事
    怎么快速适应新的测试工作?
    xshell如何导出日志文件和上传文件
    jmeter+fiddler高效率整理接口脚本
    python-用requests库处理form-data格式的参数
    软件自动化测试工程师面试题集锦(4)
    shell脚本批量检查某个或多个服务的端口和进程是否正常
  • 原文地址:https://www.cnblogs.com/jtlgb/p/8514305.html
Copyright © 2011-2022 走看看