Struts2 Interceptor 的一个诡异问题

之前开发了一个web应用程序,开始的架构是用JSP+Servlet+JavaBean这种最原始的三层机构。但是随着后来业务的发展和对系统本身的要求,我把它迁移到了SSH2框架上。在集成Struts2的时候发生了一个诡异的问题。

我之前写了一个Filter(暂称其为loginFilter),作用是可以帮助用户自动登录(如果用户把用户信息保存在cookies里面,则自动登录).通过参考Struts2的文档,我打算用Interceptor来替代原先的这个Filter,不过这样做的结果出现了诡异的问题。

虽然Interceptor可以执行完成并且User对象已经创建并且放入Session中,跳转回main.jsp的时候还是显示不了有USER的界面。但是再刷新一下main.jsp就可以显示出USER对应的界面了,真是怪事,百思不得其解。

   看了一下Struts2的文档,里面有这么一段:

The intercept method is where the interceptor code is written. Just like an action method, intercept returns a result used by Struts to forward the request to another web resource. Calling invoke on the parameter of type ActionInvocation will execute the action (if this is the last interceptor on the stack) or another interceptor.

Keep in mind that invoke will return after the result has been called (eg. after you JSP has been rendered), making it perfect for things like open-session-in-view patterns. If you want to do something before the result gets called, you should implement a PreResultListener.

看了下我的Interceptor,最后的返回语句我写的是invocation.invoke();

按照上述文档的说明,invoke方法在返回结果之后才执行。我希望先返回到main.jsp,所以也许我应该实现PreResultListener接口并且实现它的方法beforeResult(),于是这样做了,并且在beforeResult方法里Return了一个新的Result "resultA",在Struts.xml找到action并且配置这个result,使其跳转回main.jsp.

main.jsp的user部分对应的界面可以正常显示了,不过其它部分页面加载出现了问题。经过排查,后面这个问题是由于前端在加载页面的时候才用了AJAX这样异步的操作方式。后面这个问题如果想用Interceptor来完美解决,可能需要在前端进行一部分的修改,所以我最终放弃了Intercepter的做法,这个自动登录的功能最后还是才用的Filter来做的,Filter不光过滤Action的请求,也可以过滤任何URL下的请求,所以当main.jsp请求完成的时候filter不用担心是不是异步加载的,因为加载后filter也会调用,这样才用Interceptor产生的第二个问题也解决掉了。

以后有机会我会再排查一下这个问题是否和异步加载数据有关,不过红字的部分对于Interceptor的使用是很有帮助的。

猜你喜欢

转载自whywjf.iteye.com/blog/1742255