首页 > 代码库 > java web 自定义filter

java web 自定义filter

filter顾名思义,过滤器的意思,在javaweb中的Struts就利用了这种机制去实现视图和业务分离。

这里来配置下自己的Filter来理解下Struts的内在。

在web.xml 中添加下面:

      <filter>
        <filter-name>myfilter</filter-name>
        <filter-class>sun.fifter.MyFifter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>myfilter</filter-name>
        <url-pattern>*</url-pattern>
    </filter-mapping>

这里意思是只要url的类型是* ,就会调 myfilter,

然后定义myfilter这个类:

package sun.fifter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.tools.JavaCompiler;

public class MyFifter implements  javax.servlet.Filter
{

    public MyFifter()
    {
        // TODO Auto-generated constructor stub
      
    }

    @Override
    public void destroy()
    {
        // TODO Auto-generated method stub
        System.out.println("destroy");
    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1,
            FilterChain arg2) throws IOException, ServletException
    {
        // TODO Auto-generated method stub
        System.out.println("doFilter");

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException
    {
        // TODO Auto-generated method stub
        System.out.println("init");
    }

}

这样在调用的时候:http://localhost:8080/WebProject1/index.html

 

控制台就会输出;

技术分享

 

java web 自定义filter