java中如何用过滤器来拦截用户不允许访问的网页(通过地址栏来进行拦截)

过滤器用来拦截用户不允许访问的网页(通过地址栏来进行拦截)

例如:等用户在地址栏输入访问地址后跳转时进行拦截,只允许访问集合中存在的这些网页,在web.xml中先进行如下配置


FilterSerlvet
com.zt.filter.FilterSerlvet

code
utf-8



FilterSerlvet
/*

过滤器的写法

public class FilterSerlvet implements Filter {

               private List paths =new ArrayList();//实例化一个装路径的集合

      public void doFilter(ServletRequest arg0, ServletResponse arg1,
                         FilterChain chain ) throws IOException, ServletException {
               HttpServletRequest request =(HttpServletRequest) arg0;
               HttpServletResponse response =(HttpServletResponse) arg1;
               String contextPath =request.getContextPath();
               String path =request.getRequestURL().toString();
               System.out.println(contextPath);//  20170512filter2
               System.out.println(path);//  http://localhost:8080/20170512filter2/user1/list.jsp
               int num =path.indexOf(contextPath)+contextPath.length();
               String relpath =path.substring(num+1);
               if (paths.contains(relpath)) {
                         chain.doFilter(request, response);
               }else {
                         response.sendRedirect("../index.jsp");
               }

      }
      public void init(FilterConfig arg0) throws ServletException {
               // TODO Auto-generated method stub

           //将允许访问的网页路径放入集合中,实际开发中应该是从数据库中取允许访问的路径
               paths.add("user1/list.jsp");
               paths.add("user2/list.jsp");
               paths.add("user3/list.jsp");
               paths.add("index.jsp");
      }
      public void destroy() {
               // TODO Auto-generated method stub

      }

}

你可能感兴趣的:(mvc)