在使用spring容器的web应用中,业务对象间的依赖关系都可以用context.xml文件来配置,并且由spring容器来负责依赖对象 的创建。如果要在servlet中使用spring容器管理业务对象,通常需要使用WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext())来获得WebApplicationContext,然后调用WebApplicationContext.getBean("beanName")来获得对象的引用,这实际上是使用了依赖查找来获得对象,并且在servlet代码中硬编码了应用对象的bean名字。为了能在servlet中感知spring中bean,可采用如下步骤来实现:
1- 将filter或servlet作为bean定义在context.xml文件中,和要应用的bean定义放在一起;
2- 实现一个代理servlet,该servlet用WebApplicationContext来获得在context.xml中定义的servlet的对象,并将任务委托给context.xml中定义的servlet
3- 在web.xml中用ContextLoaderListener来初始化spring 的context,同时在代理servlet的定义中用初始化参数来定义context.xml中servlet的bean名字。
4- 在web.xml中定义代理servlet的mapping.
利用这种方式就将servlet和业务对象的依赖关系用spring 来进行管理,并且不用在servlet中硬编码要引用的对象名字。

具体实例如下:

Filter

1.       在applicationContext.xml中定义filter

  1. <bean id="springFilter" class="com.netqin.filter.SpringFilter">
  2. <property name="name">
  3. <value>SpringFilter</value>
  4. </property>
  5. </bean>

说明:com.netqin.filter.SpringFilter为实现了javax.servlet.Filter接口的filter

2.       实现filter代理

实际上,filter代理不需要我们自己来实现,Spring提供了两种现成的filter代理

org.springframework.security.util.FilterToBeanProxy,

org.springframework.web.filter.DelegatingFilterProxy,两者只是在web.xml中的配置上略有不同,下面就让我们一起看看如何在web.xml中进行配置。

3.       配置web.xml

初始化spring的context

因为是使用spring来管理,所以在使用filter前先要初始化spring的context,一般来说配置如下:

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>

/WEB-INF/applicationContext.xml

</param-value>

</context-param>

<listener>

<listener-class>

org.springframework.web.context.ContextLoaderListener

</listener-class>

</listener>

Filter配置: FilterToBeanProxy

<filter>

<filter-name> springFilter </filter-name>

<filter-class>

org.springframework.security.util.FilterToBeanProxy

</filter-class>

<init-param>

<param-name>targetBean</param-name>

<param-value>springFilter</param-value>

</init-param>

</filter>

说明:需要为FilterToBeanProxy提供上下文参数,这里我们配置的是targetBean属性,它告诉spring在context中查找的bean名称,所以当请求被过滤器拦截后FilterToBeanProxy会在applicationContext.xml中会查找id为springFilter的bean.

我们也可以配置targetClass属性,意思就是查找该类型的bean.

<filter>

<filter-name>springFilter</filter-name>

<filter-class>

org.springframework.web.filter.DelegatingFilterProxy

</filter-class>

</filter>

说明:使用DelegatingFilterProxy时不需要配置任何参数,spring会根据filter-name的名字来查找bean,所以这里spring会查找id为springFilter的bean.

配置filter的mapping

<filter-mapping>

<filter-name>springFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

OK!filter配置完成。推荐使用DelegatingFilterProxy,应为配置上更简单。

Servlet

Servlet的配置与Filter的配置十分相似

1.       在applicationContext.xml中定义servlet

<bean id="springServlet" class="com.netqin.servlet.SpringServlet">

<property name="name">

<value>SpringServlet</value>

</property>

</bean>

说明:com.netqin.servlet.SpringServlet继承自

javax.servlet.http.HttpServlet

2.       实现servlet代理

与filter不同,spring没有为servlet提供代理实现,需要我们自己来创建,不过放心,创建一个servlet代理十分简单,一个具体的实现如下:

import java.io.IOException;

import javax.servlet.GenericServlet;

import javax.servlet.Servlet;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import org.springframework.web.context.WebApplicationContext;

import org.springframework.web.context.support.WebApplicationContextUtils;

public class ServletToBeanProxy extends GenericServlet {

private String targetBean;

private Servlet proxy;

public void init() throws ServletException {

this.targetBean = getInitParameter("targetBean");

getServletBean();

proxy.init(getServletConfig());

}

public void service(ServletRequest req, ServletResponse res)

throws ServletException, IOException {

proxy.service(req, res);

}

private void getServletBean() {

WebApplicationContext wac = WebApplicationContextUtils

.getRequiredWebApplicationContext(getServletContext());

this.proxy = (Servlet) wac.getBean(targetBean);

}

}

说明:相信看了代码就明白了,它利用targetBean属性在spring中查找相应的servlet,

这很像FilterToBeanProxy的方式,所以我为其取名为ServletToBeanProxy。当然,我们也可以使用类似于DelegatingFilterProxy的方式,只需要将上述代码中标记为黄色的部分修改为this.targetBean=this.getServletName();即可,我们相应的命名为DelegatingServletProxy。

3.       配置web.xml

初始化spring的context

与filter中的说明一致,不再赘述。

Servlet配置:

ServletToBeanProxy

<servlet>

<servlet-name>springServlet</servlet-name>

<servlet-class>

com.netqin.servlet.proxy.ServletToBeanProxy

</servlet-class>

<init-param>

<param-name>targetBean</param-name>

<param-value>springServlet</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet>

<servlet-name>springServlet</servlet-name>

<servlet-class>

com.netqin.servlet.proxy.DelegatingServletProxy

</servlet-class>

<load-on-startup>1</load-on-startup>

</servlet>

4.       配置servlet的mapping

<filter-mapping>

<filter-name>springServlet</filter-name>

<url-pattern>/servlet/*</url-pattern>

</filter-mapping>

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

例子代码如下:
(1)代理servlet:
=======================================================================
ackage che
import java.io.IOExceptio
import javax.servlet.GenericServlet;import javax.servlet.Servlet;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse
import org.springframework.web.context.WebApplicationContext;import org.springframework.web.context.support.WebApplicationContextUtil
ublic class ServletToBeanProxy extends GenericServlet {  private String targetBea
rivate Servlet proxy;   public void init() throws ServletException {  System.out.println("proxy init");    this.targetBean = getInitParameter("targetBean");    getServletBean();    proxy.init(getServletConfig()); }
ublic void service(ServletRequest req, ServletResponse res)   throws ServletException, IOException {    proxy.service(req, res)
rivate void getServletBean() {    WebApplicationContext wac =   WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());  this.proxy = (Servlet)wac.getBean(targetBean);   }  }
=================================================================================
(2)web.xml中配置
<context-param>  <param-name>contextConfigLoaction</param-name>  <param-value>/WEB-INF/context.xml</param-value> </context-param>  <listener>  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet>  <servlet-name>ProxyBean</servlet-name>  <servlet-class>chen.ServletToBeanProxy</servlet-class>  <init-param>   <param-name>targetBean</param-name>   <param-value>servletBean</param-value>  </init-param> </servlet>
<servlet-mapping>  <servlet-name>ProxyBean</servlet-name>  <url-pattern>/ProxyBean</url-pattern> </servlet-mapping>
(3) 完成实际任务的servlet定义,该servlet会引用另一个Book的对象
======================= ServletBean.java=======================
ackage che
import java.io.IOExceptio
import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse
/** * Servlet implementation class for Servlet: ServletBean * */ public class ServletBean extends javax.servlet.GenericServlet implements javax.servlet.Servlet {
rivate Book book;      public ServletBean() {  super(); }      public void init() throws ServletException {   super.init();   }
ublic void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {  book.showInfo();   }
ublic Book getBook() {  return book; }
ublic void setBook(Book book) {  this.book = book; }   }
================================Book.java==============================
ackage che
ublic class Book { private String isbn; private String name;    public String getIsbn() {  return isbn; } public void setIsbn(String isbn) {  this.isbn = isbn; } public String getName() {  return name; } public void setName(String name) {  this.name = name; }   public void showInfo() {  System.out.println("book info..."); }  }
(4) context.xml配置
<beans> <bean id="book" class="chen.Book"/> <bean id="servletBean" class="chen.ServletBean">  <property name="book">   <ref bean="book"/>  </property> </bean></beans>
注意,在web.xml中并不出现ServletBean的说明,取而代之的是ServletToBeanProxy的说明,并用初始化参数targetBean来定义要代理的Servlet在context.xml中的名字。
当在浏览器中输入http://localhost/webcontext/ProxyBean时 ,spring将会创建ServletBean一个实例,其引用的Book实例也会被创建。
对Filter,springframework1.2以后自带了org.springframework.web.filter.DelegatingFilterProxy 来实现Filter和业务对象之间的代理,不需要自行开发了。

Spring管理Filter和Servlet(在servlet中注入spring容器中的bean)的更多相关文章

  1. SpringBoot 源码解析 (七)----- Spring Boot的核心能力 - 自定义Servlet、Filter、Listener是如何注册到Tomcat容器中的?(SpringBoot实现SpringMvc的原理)

    上一篇我们讲了SpringBoot中Tomcat的启动过程,本篇我们接着讲在SpringBoot中如何向Tomcat中添加Servlet.Filter.Listener 自定义Servlet.Filt ...

  2. SpringBoot下使用AspectJ(CTW)下不能注入SpringIOC容器中的Bean

    SpringBoot下使用AspectJ(CTW)下不能注入SpringIOC容器中的Bean 在SpringBoot中开发AspectJ时,使用CTW的方式来织入代码,由于采用这种形式,切面Bean ...

  3. 非spring组件servlet、filter、interceptor中注入spring bean

    问题:在filter和interceptor中经常需要调用Spring的bean,filter也是配置在web.xml中的,请问一下这样调用的话,filter中调用Spring的某个bean,这个be ...

  4. Spring 管理Filter和Servlet

    本文转载自:http://www.open-open.com/lib/view/open1417248512252.html 在使用spring容器的web应用中,业务对象间的依赖关系都可以用cont ...

  5. 如何使用Spring管理Filter和Servlet

    在使用spring容器的web应用中,业务对象间的依赖关系都可以用context.xml文件来配置,并且由spring容器来负责依赖对象 的创建.如果要在filter或者servlet中使用sprin ...

  6. 如何在静态方法或非Spring Bean中注入Spring Bean

           在项目中有时需要根据需要在自己new一个对象,或者在某些util方法或属性中获取Spring Bean对象,从而完成某些工作,但是由于自己new的对象和util方法并不是受Spring所 ...

  7. Java(多)线程中注入Spring的Bean

    问题说明 今天在web应用中用到了Java多线程的技术来并发处理一些业务,但在执行时一直会报NullPointerException的错误,问题定位了一下发现是线程中的Spring bean没有被注入 ...

  8. java多线程中注入Spring对象问题

    web应用中java多线程并发处理业务时,容易抛出NullPointerException. 原因: 线程中的Spring Bean没有被注入.web容器在启动时,没有提前将线程中的bean注入,在线 ...

  9. main方法中注入Spring bean

    在有些情况下需要使用main使用Spring bean,但是main方法启动并没有托管给Spring管理,会导致bean失败,报空指针异常. 可以使用 ClassPathXmlApplicationC ...

随机推荐

  1. 让uboot的tftp支持上传功能

    转载:http://blog.chinaunix.net/uid-20737871-id-2124122.html uboot下的tftp下载功能是非常重要和常见的功能.但是偶尔有些特殊需求的人需要使 ...

  2. 局部描述符表LDT的作用+定义+初始化+跳转相关

    [0]写在前面 0.1)本代码的作用: 旨在说明局部描述符表的作用,及其相关定义,初始化和跳转等内容: 0.2)文末的个人总结是干货,前面代码仅供参考的,且source code from orang ...

  3. 目标检测之基础hessian matrix ---海森矩阵

    就是海赛(海色)矩阵,在网上搜就有. 在数学中,海色矩阵是一个自变量为向量的实值函数的二阶偏导数组成的方块矩阵, Hessian矩阵是多维变量函数的二阶偏导数矩阵,H(i,j)=d^2(f)/(d(x ...

  4. PHP操作:将数据库中的数据保存到Word、Excel中。

    1.首先要把word.excel表放到文件的根目录下 2.定义了一个word类 <?php class word { function start() { ob_start(); ob_star ...

  5. 【BZOJ4166】月宫的符卡序列 Manacher+hash

    [BZOJ4166]月宫的符卡序列 题解:题倒不难,就是有点恶心. 首先学习回文串的时候一定学到了这样一个结论:一个长度为n的串的本质不同的回文子串数量不超过n个. 那么我们就可以试图将所有回文串的价 ...

  6. 【BZOJ2654】tree 二分+最小生成树

    [BZOJ2654]tree Description 给你一个无向带权连通图,每条边是黑色或白色.让你求一棵最小权的恰好有need条白色边的生成树. 题目保证有解. Input 第一行V,E,need ...

  7. EasyPlayerPro windows播放器本地配置文件配置方法介绍

    需求背景 应EasyPlayerPro某客户需求,在EasyPlayerPro启动时,自动播放指定的url源, 不需要每次都去手动填写, 且实现自动播放,不需要手动的单击播放按钮: 为响应该需求,特增 ...

  8. python中的特殊用法

    1 别名 from xxx import xxx as xxx;

  9. (1)Web 应用是一个状态机,视图与状态是一一对应的。 (2)所有的状态,保存在一个对象里面。

    Redux 入门教程(一):基本用法 - 阮一峰的网络日志 http://www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_one_basic_u ...

  10. Django框架ORM常用参数汇总_模型层

    primary_key 如果为True,那么这个字段就是模型的主键. 如果你没有指定任何一个字段的primary_key=True, Django就会自动添加一个IntegerField字段做为主键, ...