如何在Java Filter 中注入 Service

2025-03-19 13:27:34
推荐回答(3个)
回答1:

0
既然你要需要统计网站流量数据,使用filter,而这个filter使用了一个Service,肯定是是用其一个方法。

照这么看着,我看根本不需要这个filter,在调用这个方法之前使用一个拦截器,亦称spring方法拦截器。在这个拦截器中的继承方法中统计网站流量数据。

==================================================
或者:用 硬编码 在Filter里 new 一个 Service 了出来

回答2:

1. 如何获取 ServletContext:
1)在javax.servlet.Filter中直接获取
ServletContext context = config.getServletContext();

2)在HttpServlet中直接获取
this.getServletContext()

3)在其他方法中,通过HttpServletRequest获得
request.getSession().getServletContext();
2. WebApplicationContext 与 ServletContext (转自:http://blessht.iteye.com/blog/2121845):
Spring的 ContextLoaderListener是一个实现了ServletContextListener接口的监听器,在启动项目时会触发contextInitialized方法(该方法主要完成ApplicationContext对象的创建),在关闭项目时会触发contextDestroyed方法(该方法会执行ApplicationContext清理操作)。
ConextLoaderListener加载Spring上下文的过程
①启动项目时触发contextInitialized方法,该方法就做一件事:通过父类contextLoader的initWebApplicationContext方法创建Spring上下文对象。
②initWebApplicationContext方法做了三件事:创建 WebApplicationContext;加载对应的Spring文件创建里面的Bean实例;将WebApplicationContext放入 ServletContext(就是Java Web的全局变量)中。
③createWebApplicationContext创建上下文对象,支持用户自定义的上下文对象,但必须继承自ConfigurableWebApplicationContext,而Spring MVC默认使用ConfigurableWebApplicationContext作为ApplicationContext(它仅仅是一个接口)的实 现。
④configureAndRefreshWebApplicationContext方法用 于封装ApplicationContext数据并且初始化所有相关Bean对象。它会从web.xml中读取名为 contextConfigLocation的配置,这就是spring xml数据源设置,然后放到ApplicationContext中,最后调用传说中的refresh方法执行所有Java对象的创建。
⑤完成ApplicationContext创建之后就是将其放入ServletContext中,注意它存储的key值常量。

回答3:

配置一:
Java代码  
  
        DelegatingFilterProxy  
        org.springframework.web.filter.DelegatingFilterProxy  
          
            targetBeanName  
            myFilter         //自己过滤器的名字  
        
  
          
            targetFilterLifecycle  
            true  
        
  
    
  
  
      
        DelegatingFilterProxy  
        /*  
    
  
 
配置二:
Java代码  
  
        myFilter  
        org.springframework.web.filter.DelegatingFilterProxy  
          
            targetFilterLifecycle  
            true  
        
  
    
  
  
      
        DelegatingFilterProxy  
        /*  
    
  
 
方法一或者二不同的地方就是在web.xml中的写法不同而已没有太大的区别,配完web.xml之后还要配置 applicationContext.xml中的bean。
applicationContext.xml配置:
Java代码  
 //指名具体的filter类  
                        //需要注入的具体参数  
          
      
   
 
 
如果使用注解:
Java代码  
@Component("tjFilter")   
public class TjFilter implements Filter {  
  
    @Resource(name="historyManager")  
    private HistoryManager historyManager;  
  
    public void destroy() {  
        // TODO Auto-generated method stub  
  
    }  
   .....  
}