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>
  • 相关阅读:
    hdu 1213 (How Many Tables)(简单的并查集,纯模板)
    Android 开发 -------- 自己定义View 画 五子棋
    POJ 2472 106 miles to Chicago
    android application
    Effective C++:条款39:明智而审慎地使用private继承
    云计算统一办公运营平台服务能力设计方案
    LCA 近期公共祖先 小结
    MFC exe使用C++ dll中的std::string 崩溃
    函数调用堆栈图
    【cocos2d-js官方文档】二十、moduleConfig.json
  • 原文地址:https://www.cnblogs.com/jtlgb/p/8514305.html
Copyright © 2011-2022 走看看