zoukankan      html  css  js  c++  java
  • servlet filter中使用autowired无法注入

    问题:

    我们为了避免未经授权的人直接通过url访问我们的页面,配置了如下filter

      <!-- 登录过滤器 -->
      <filter>
        <filter-name>sessionFilter</filter-name>
        <filter-class>com.sung.risk.client.filter.SessionFilter</filter-class>
      </filter>
      <filter-mapping>
        <filter-name>sessionFilter</filter-name>
        <url-pattern>*.html</url-pattern>
      </filter-mapping>

    在filter中会去验证用户是否携带了某个cookie,然后去redis查询该cookie的值是否关联了用户信息,如果关联了,则filter放过;否则返回未认证。

    一开始打算注入以下服务(该服务主要进行去redis认证):

    @Autowired
    SessionService sessionService;

    然而,事实证明,注入失败。

    我们的解决办法:

            ServletContext context = request.getServletContext();
            ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
            SessionService sessionService = ctx.getBean(SessionService.class);

    在filter上加spring的注解是无用的,只会生成两个该filter的实例A和B(A:tomcat之类的容器管理,B为spring管理)。

    A可以读取web.xml中的配置信息,A是没有办法autowired的;B则可以用@autowired注入。但是我们的请求最终进入的是A,所以A中的注入的bean无效。

  • 相关阅读:
    著名的二分查找的BUG
    C/C++ static用法
    浅谈C++虚函数
    git备忘(长久更新)
    【经典问题】最大子串和
    水波纹效果
    博客迁址 xpeng.scorpionstudio.com
    终于,我们的新产品Fotor Slideshow Maker上线了!!
    分享一款浏览器扩展--美图搜索-图片搜索工具
    分享网页微信防撤回插件
  • 原文地址:https://www.cnblogs.com/grey-wolf/p/6962660.html
Copyright © 2011-2022 走看看