歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

在Servlet Filter中使用Spring容器

定義一個filter, 實現ApplicationContextAware接口:

public class CacheFilter implements Filter, ApplicationContextAware {
    private static ApplicationContext ctx; // 必須聲明為static

    @Override
    public void init(FilterConfig config) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        filterChain.doFilter(servletRequest, servletResponse);

    }

    @Override
    public void destroy() {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        CacheFilter.ctx = applicationContext; // 保存spring容器到static變量中
    }

然後,在spring配置文件中配置該filter,使之成為容器管理的bean:

<beans:bean id="cacheFilter" class="com.fh.taolijie.servlet.CacheFilter" />

最後,在web.xml中聲明過濾器:

<filter>
        <filter-name>Cache Filter</filter-name>
        <filter-class>com.fh.taolijie.servlet.CacheFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Cache Filter</filter-name>
        <servlet-name>appServlet</servlet-name>
    </filter-mapping>

這時,我們就可以在doFilter()方法中直接通過ApplicationContext檢索需要的bean了:

StringRedisTemplate redis = (StringRedisTemplate)ctx.getBean("redisTemplate");

Copyright © Linux教程網 All Rights Reserved