Guice中使用Filter

1.创建自己的Filter

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 com.google.inject.Singleton;

@Singleton
public class InitConfigFilter implements Filter{

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain chain) throws IOException, ServletException {
		System.out.println("ok");
		chain.doFilter(arg0, arg1);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
	}

}

2.在GuiceServletContextListener中调用Guice.createInjector(new ServletModule());方法

import test.web.filter.InitConfigFilter;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
import com.google.inject.servlet.ServletModule;

public class ServletConfigListener extends GuiceServletContextListener {

	@Override
	protected Injector getInjector() {
		return Guice.createInjector(new ServletModule(){

			@Override
			protected void configureServlets() {
				filter("/*").through(InitConfigFilter.class);
			}
			
		});
	}

}

  如果Filter需要初始化参数,可用filter("/*").through(InitConfigFilter.class,Map类型参数列表).

3.配置web.xml

<filter>
	<filter-name>GuiceFilter</filter-name>
	<filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
	<filter-name>GuiceFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
	<listener-class>test.web.ServletConfigListener</listener-class>
</listener>

你可能感兴趣的:(filter,Guice)