首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Spring治理filter和servlet(转)

2012-11-01 
Spring管理filter和servlet(转)Spring管理filter和servlet在使用spring容器的web应用中,业务对象间的依赖

Spring管理filter和servlet(转)
Spring管理filter和servlet
  在使用spring容器的web应用中,业务对象间的依赖关系都可以用context.xml文件来配置,并且由spring容器来负责依赖对象  的创建。如果要在filter或者servlet中使用spring容器管理业务对象,通常需要使用

WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext())来获得WebApplicationContext,然后调用WebApplicationContext.getBean("beanName")来获得对象的引用,这实际上是使用了依赖查找来获得对象,并且在filter或者servlet代码中硬编码了应用对象的bean名字。为了能在filter或者servlet中感知spring中bean,可采用如下步骤来实现:

1-  将filter或者servlet作为bean定义在context.xml文件中,和要应用的bean定义放在一起;

2-  实现一个filter代理或者servlet代理,该代理用WebApplicationContext来获得在context.xml中定义的filter或者servlet的对象,并将任务委托给context.xml中定义的filter或者servlet

3-  在web.xml中用ContextLoaderListener来初始化spring  的context,同时在filter代理或者servlet代理的定义中用初始化参数来定义context.xml中filter或者servlet的bean名字(或者直接受用代理的名称获得相应的filter或者servlet的名称)。

4-  在web.xml中定义filter代理或者servlet代理的mapping.

利用这种方式就将filter或者servlet和业务对象的依赖关系用spring  来进行管理,并且不用在servlet中硬编码要引用的对象名字。



具体实例如下:
Filter
1.       在applicationContext.xml中定义filter

<filter-mapping>        <filter-name>springServlet</filter-name>        <url-pattern>/servlet/*</url-pattern>    </filter-mapping>

OK!servlet的配置完成。推荐使用DelegatingServletProxy,应为配置上更简单。

热点排行