双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

如何在filter中使用String的IOC

王者_来归 王者_来归 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
如题,需求描述如下:
在filter中把用户点击的URL、IP、cookie、时间等信息获取出来,保存到数据库,用于分析哪个url使用的最多,同时也作为一个系统日志。
问题:
获取到信息后,要在filter中使用String的注解bean,然后把数据保存。但是,根据系统启动时加载顺序:listener >> filter >> servlet >> spring,在filter加载的时候,spring中的bean还没有加载,这就导致我在filter中使用bean时,bean为null。

在网上找了几种办法,试了都不行:
方法一:

WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
this.baseDao = (ITestDao<Test>)webApplicationContext.getBean("testDao");

其中,ITestDao为接口类,在实现类中有一个注解:@Component("testDao")
这种方式报错信息如下:
org.hibernate.HibernateException: No Session found for current thread


方法二:
web.xml中:

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

<filter-mapping>
<filter-name>DelegatingFilterProxy</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

在application-beans.xml中:

<bean id="myFilter"
class="com.Test.filter.TestFilter">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

在TestFilter中:

this.sessionFactory.getCurrentSession().save(test);

这个也报错,原因为this.sessionFactory.getCurrentSession()为null了。

我使用的是:struts2+hibernate4+spring4

请各位给点化一下,谢谢!
...全文

相关推荐

评论 12
收藏 已收藏
分享
返回顶部
王者_来归
Java EE 67,535 成员 225,843 内容