读书人

施用Struts2拦截器需要注意的地方

发布时间: 2012-09-15 19:09:28 作者: rapoo

使用Struts2拦截器需要注意的地方

今天在写拦截器的时候发现一个貌似属于bug的问题

我使用的版本是2.1.8

?

当访问一个满足拦截器拦截条件的请求时,虽然代码已经执行进入拦截器,并且返回结果也是拦截后改变的跳转结果,但是却没有按照返回结果跳转,而是依旧进入了action。

?

源代码是这样的:

public String intercept(ActionInvocation invocation) throws Exception {ActionContext ctx = ActionContext.getContext();String result = invocation.invoke();Map session = ctx.getSession();if ("guest".equals(type)) {if (null == session.get("guest")) {result = Action.LOGIN;}    } else {    if (null == session.get("user")) {result = Action.LOGIN;}    }return result;}

?

这里当用户session失效后,跳转的依然是action的指向,而不是我的login指向,这是一个很奇怪的问题

在反复检查后,终于发现,原来是invocation.invoke()在作怪

只要在返回结果前先调用了这个方法,那么无论返回结果改成什么,都不影响action的正常跳转,导致拦截跳转效果失效。

?

最终改动后的有效代码如下:

public String intercept(ActionInvocation invocation) throws Exception {ActionContext ctx = ActionContext.getContext();String result = "";Map session = ctx.getSession();if ("guest".equals(type)) {if (null == session.get("guest")) {result = Action.LOGIN;}    } else {    if (null == session.get("user")) {result = Action.LOGIN;}    }return "".equals(result) ? invocation.invoke() : result;}

?

读书人网 >软件架构设计

热点推荐