`
xiaofengtoo
  • 浏览: 484802 次
  • 性别: Icon_minigender_1
  • 来自: xiamen
社区版块
存档分类
最新评论

listener、filter、servlet、beans执行顺序如何

    博客分类:
  • IT
阅读更多

在典型的J2EE里面

可以肯定的是,加载顺序与他们在web.xml 文件中的先后顺序无关。
web.xml中的加载顺序为:listener >> filter >> servlet >> spring 其中filter的执行顺序是filter- mapping 在web.xml中出现的先后顺序。

加载顺序会影响对spring bean的调用。比如filter 需要用到bean ,但是加载顺序是先加载filter 后加载spring,则filter中初始化操作中的bean为null。所以,如果过滤器中要使用到 bean,可以将spring 的加载改成Listener的方式。如下所示(灰色部分为可选):

 <context-param> 
        <param-name>contextConfigLocation</param-name> 
        <param-value>classpath*:spring*.xml</param-value> 
    </context-param> 
	<listener>
	    <listener-class>org.springframework.web.context.ContextLoaderServlet</listener-class>
	  </listener>

 在<param-value> </param-value>里指定相应的xml文件名,如果有多个xml文件,可以写在一起并用“,”号分隔。上面的applicationContext-*.xml采用通配符,
比如这那个目录下有applicationContext-ibatis-base.xml,applicationContext-action.xml,applicationContext-ibatis-dao.xml等文件,都会一同被载入。

 

另:如果需要在Listener 中调用了sping的bean,可是由于执行顺序的原因,很是苦恼

参考:技术积累池

 

import java.util.Timer;  
import javax.servlet.ServletContext; 
import javax.servlet.ServletContextEvent;  
import javax.servlet.ServletContextListener;  
import org.springframework.web.context.WebApplicationContext;  
import org.springframework.web.context.support.WebApplicationContextUtils;  

/** 
 * 任务监听器 
 *  
 * @author 忧里修斯 
 * 
 */  
public class TaskListener implements ServletContextListener {  
    public void contextDestroyed(ServletContextEvent context) {  
    }  
    public void contextInitialized(ServletContextEvent context) {  
       ServletContext servletContext = context.getServletContext();  
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);  
       SheduleTask sheduleTask = (SheduleTask) wac.getBean("sheduleTask");  
        Timer timer = new Timer();  
        //每隔30分钟执行一次  
//      timer.schedule(new SheduleTask(), 0,1000*60*30);  
        timer.schedule(sheduleTask, 0,1000*60*30);  
    }  
}  

 可是老是出现:

No WebApplicationContext found: no ContextLoaderListener registered?

 

参考了:关于web.xml中listener的执行顺序问题

 

思路就是,既然listener的顺序是不固定的,那么我们可以整合两个listener到一个类中,这样就可以让初始化的顺序固定了。我就是重写了org.springframework.web.context.ContextLoaderListener这个类

 

解决方法是:

 

public class Listener  extends ContextLoaderListener  implements ServletContextListener {
     public void contextInitialized(ServletContextEvent event) {
        super.contextInitialized(event);
        //TODO 写你的操作
   }
  public void contextDestroyed(ServletContextEvent event) {	
            //TODO 写你的操作		
		super.contextDestroyed(event);

	}
}
 

然后在web.xml中配置

 

<listener>
	    <listener-class>com.Listener</listener-class>
</listener>
 

 

分享到:
评论
1 楼 francis.xjl 2012-12-03  
这个做法,不错! 但感觉还是有点别扭,不知道有没有更好的方法。

相关推荐

Global site tag (gtag.js) - Google Analytics