1、常识:
PreResultListener 是一个监听器接口,它可以在 Action 完成控制处理之后,系统转入实际的物理视图之间被回调。
Struts2应用可以为Action、拦截器添加 PreResultListener 监听器,添加PreResultListener 监听器通过 ActionInvocation 的 addPreResultListener() 方法完成。 一旦为 Action 添加了PreResultListener 监听器,该监听器就可以在应用转入实际物理视图之前回调该监听器的 beforeResult() 方法; 一旦为拦截器添加了 PreREsultListener 监听器,该监听器会对该拦截器所拦截的所有 Action 都起作用。
2、为action添加
<span style="color:#444444;">package ray.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
import ray.listener.PreResultListener;
import ray.tools.Consts;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
public class LogoutAction extends DefaultAction implements ServletRequestAware {
private static final long serialVersionUID = 1L;
private HttpSession session = null;
@Override
public void setServletRequest(HttpServletRequest request) {
session = request.getSession(false);
}
public String logout() {
/*
* 为action添加preREsultListerner
*/
</span><span style="color:#ff0000;">ActionInvocation invocation = ActionContext.getContext().getActionInvocation();
invocation.addPreResultListener(new PreResultListener());</span><span style="color:#444444;">
if (null != session) {
session.removeAttribute(Consts.USERSESSION);
session.invalidate();
}
return Action.LOGIN;
}
}
</span>
自己定义一个Listerner:
package ray.listener;
import com.opensymphony.xwork2.ActionInvocation;
public class PreResultListener implements com.opensymphony.xwork2.interceptor.PreResultListener{
@Override
public void beforeResult(ActionInvocation invocation, String resultCode) {
System.out.println("在视图返回前调");
System.out.println("返回的视图名称为: " + resultCode);
invocation.getInvocationContext().put("extData", new java.util.Date()+"由"+resultCode+"逻辑视图转入");
}
}
3、为拦截器添加PreResultListener
package ray.interceptors;
import ray.listener.PreResultListener;
import ray.tools.Consts;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class LoginInterceptor extends AbstractInterceptor {
private static final long serialVersionUID = 1L;
private ActionContext context = null;
@Override
public String intercept(ActionInvocation invocation) throws Exception {
invocation.addPreResultListener(new PreResultListener());
this.context = invocation.getInvocationContext();
Object object = context.getSession().get(Consts.USERSESSION);
if(object == null){
return Action.LOGIN;
} else {
return invocation.invoke();
}
}
}