过滤器(路径拦截)

  • 概述
    过滤器是服务器与客户端请求与响应的中间层组件,在实际项目开发中过滤器主要用于对浏览器的请求进行过滤处理,将过滤后的请求再转给下一个资源。与其他的WEB应用程序组件不同的是,过滤器是采用了“链”的方式进行处理的。
  • 实现简单的路径拦截
package com.filterTest;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class FilterTest
 */
public class FilterTest implements Filter {

    /**
     * Default constructor. 
     */
    public FilterTest() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
		System.out.println("FilterTest.destroy()");
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		HttpServletRequest req=(HttpServletRequest) request;
		String requestURI = req.getRequestURI();
		if (requestURI.indexOf("index.jsp")!=-1) {
			req.getRequestDispatcher("login.jsp").forward(req, response);
		}else{
			chain.doFilter(request, response);
		}
			
		// pass the request along the filter chain
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("FilterTest.init()");
	}

}

web.xml



  ListenerPractice
  
  
  filtertest
  com.bjsxt.filterTest.FilterTest
  
  
  filtertest
  /*
  

  • 附录
    https://blog.csdn.net/kato_op/article/details/80214456
    这篇博客描述的很详细,大家可以去看看

你可能感兴趣的:(编程语言)