您的位置:首页 > 编程语言 > Java开发

Spring管理filter和servlet

2015-04-06 12:12 288 查看
在使用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中硬编码要引用的对象名字。

配置DelegatingServletProxy的常用方法见:http://blog.csdn.net/heyutao007/article/details/44900649

配置DelegatingFilterProxy的常用方法如下所示:

<filter>
<filter-name>testFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>testBean</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>testFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


含义是有一个过滤器,它指向一个bean,这个bean在spring中的名字为testBean,testBean也必需实现javax.servlet.Filter。

其他可以通过web.xml传递的参数如下:

(1) contextAttribute,使用委派Bean的范围,其值必须从org.springframework.context.ApplicationContext.WebApplicationContext中取得,默认值是session;

(2) targetFilterLifecycle,是否调用Filter的init和destroy方法,默认为false。

所以DelegationgFilterProxy的全项配置信息如下:

<filter>
<filter-name>testFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetBeanName</param-name>
<param-value>testBean</param-value>
</init-param>
<init-param>
<param-name>contextAttribute</param-name>
<param-value>session</param-value>
</init-param>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>false</param-value>
</init-param>
</filter> 
<filter-mapping>
<filter-name>testFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: