使用 Spring 容器管理 Filter

本文详细介绍了如何在Spring应用中配置Filter与监听器,通过使用代理类实现与Spring管理的服务交互,以便在Filter中调用这些服务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当我们用Filter时,往往需要使用一些辅助的service,在普通的java中,只要声明(set,get方法)后在spring-application配置文件中配置就可以了,但是由于Filter与Listener需要配置在web.xml文件中,所以它们的对象是由容器创建的。通常在Spring的application-context.xml配置文件中编写的bean由Spring负责创建,所以直接在Spring配置文件配置过滤器与监听器是无法达到注入目的的。这时就需要配置一个spring提供的代理类。web.xml中配置Filter如下:

  <filter>
      <filter-name>authFilter</filter-name>
      <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
         <init-param>
            <param-name>targetBeanName</param-name>
            <param-value>authFilterSeriver</param-value>
         </init-param>
        <init-param>
            <param-name>targetFilterLifecycle</param-name>
            <param-value>true</param-value>
        </init-param>
  </filter>

其中配置的authFilterSeriver是配置spring文件中bean的id,如下图:

<bean id="authFilterSeriver"  class="com.test.AuthFilter" ></bean>

 这样, AuthFilter中就可以调用spring管理的service了。

同理,可以自己写一个代理类,类似spring的类DelegatingFilterProxy。

package com.test.filter;  
  
import java.io.IOException;  
  
  
import javax.servlet.Filter;  
import javax.servlet.FilterChain;  
import javax.servlet.FilterConfig;  
import javax.servlet.ServletContext;  
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;  
  
  
//Filter 的代理类。系统所有的 Filter 共用此一个  
public class DelegatingFilterProxy implements Filter {  
    private String targetFilterBean;  
    private Filter proxy;  
  
    @Override  
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,  
            FilterChain filterChain) throws IOException, ServletException {  
        proxy.doFilter(servletRequest, servletResponse, filterChain);  
    }  
  
    @Override  
    public void init(FilterConfig config) throws ServletException {  
        this.targetFilterBean = config.getInitParameter("targetFilterBean");  
        ServletContext servletContext = null;  
        servletContext = config.getServletContext();  
        WebApplicationContext wac = null;  
        wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);  
        this.proxy = (Filter) wac.getBean(this.targetFilterBean);  
        this.proxy.init(config);  
    }  
  
    @Override  
    public void destroy() {}  
}  
 

  

转载于:https://www.cnblogs.com/ahang/p/5073457.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值