之前开发了一个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的使用是很有帮助的。
分享到:
相关推荐
详细介绍struts2 interceptor
Struts2拦截器(Interceptor) Struts2拦截器(Interceptor)
NULL 博文链接:https://weizhilizhiwei.iteye.com/blog/1005210
struts2 Interceptor拦截器 http://whitewolf.0fees.net
Struts2_interceptor_和_filter区别
STRUTS2:拦截器Interceptor
简单的拦截器例子,适合初学者学习,也是一个备忘录
Struts2拦截器是在访问某个Action或Action的某个方法,字段之前或之后实施拦截,并且Struts2拦截器是可插拔的,拦截器是AOP的一种实现.
用注解(annotation)方式配置struts2 (webwork) 中action的拦截器(interceptor)
struts1 拦截器功能的实现。struts2 中的interceptor很方便。但在struts1中没有这个功能,用这个插件很容易实现。
Interceptor,学习Struts 2实例,一步步教你如何实现一个示例
Struts2.x_Interceptor已经打包好了,解压后直接用,
综合使用servlet filter与struts2 interceptor对权限进行验证。
Struts2.3.6实现自定义拦截器Interceptor http://blog.csdn.net/alanchen520/article/details/34086699
struts2 拦截器_教程.zip
《Struts 2实战》结合实例介绍了Struts 2框架,主要内容包括Action、Result、Interceptor等框架组件,基于注解的配置选项等新特征,Struts 2插件 FreeMarker,如何从Struts 1和WebWork 2迁移到Struts 2,Ajax标签、...
struts2,Interceptor struts2拦截器实例,两套实例,一套是针对单个的action配置的,另一套实例是针对全局的action配置的拦截器interceptor
struts2 interceptor 的一个简单的 登录系统小demo
动作类需要实现一个 org.apache.struts2.interceptor.RequestAware 接口。所不同的是,RequestAware 将获得一个 com.opensymphony.xwork2.util.OgnlValueStack 对象,这个对象可以获得 response、request 及其他的...
07 Struts 2的基石——拦截器(Interceptor) 08 在Struts 2中实现IoC 09 在Struts 2中实现文件上传 10 在Struts 2中实现CRUD 11 Struts 2中的OGNL 12 Struts 2的新表单标志的使用 13 Struts 2与AJAX