Java的Filter过滤器

1.过滤器创建

了解过滤器常见配置含义

   
        filter名字
        对应到Java包名类名
    
    
        filter名字
        /*
    

filter-mapping标签里面还有许多参数,可以参考学习博客
特别注意标签可以同一个过滤器写多个url-pattern
标签还可带参传入到java类中,使用
在web.xml创建过滤器

      
        ElectronicFilter
        com.chinasoft.it.attendance.filter.ElectronicFilter
    
    
        ElectronicFilter
        /*
    

2.Java类创建

1>.实现Filter 接口
2>.init方法可读取web.xml中参数值
3>.重写doFilter方法,实现自己所要的功能。
4>.如果不过滤走filterChain.doFilter(request, response)方法;
public class FilterName implements Filter {

    protected String ip = "";
    protected List listUrl;

    /**
     * @see Filter#destroy()
     */
    public void destroy() {
    }

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain filterChain) throws IOException, ServletException {

        String ipRemoteAddr = request.getRemoteAddr();//读取发送请求IP地址
        //String reqUrl = ((HttpServletRequest) request).getRequestURI();

        if (!listUrl.contains(ipRemoteAddr)) {
            response.setCharacterEncoding("gb2312");
            PrintWriter out = response.getWriter();
            out.print("

IP限制!

"); } else { filterChain.doFilter(request, response); } } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig filterConfig) throws ServletException { } }

你可能感兴趣的:(Java的Filter过滤器)