package com.neil;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.Action;
import com.derby.dms.domain.User;
import com.derby.dms.util.Constant;
import java.util.Map;
/*
要开发自己的拦截器类,必须实现com.opensympony.xwork2.interceptor.Interceptor接口,该接口必须
要实现三个方法 void destory() void init() String intercept(ActionInvocation invocation) throws Exception
init(): 在该拦截器被执行之前,系统将回调此方法,此方法只执行一次。因此,该方法的方法体主要用于打开一次性资源
例如:数据库连接等。 ,
destory(): 在该拦截器被销毁之前,系统将回调此方法。该方法用于销毁在init()方法里打开的资源。
intercept(ActionInvocation invocation) : 该方法是用户需要实现的拦截动作,就像Action的execute方法一样,
intercept会返回一个字符串作为逻辑视图。ActionInvocation参数包含了被拦截的Action的引用,可以通过调用
该参数的invoke方法,将控制权转给下一个拦截器,或者转给Action的execute方法。
struts2 还提供了一个AbstractInterceptor类,该类提供了一个init和destory方法的空实现,如果我们实现的拦截器
不需要申请资源,则可以无需实现这两个方法。继承该类就可以了
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.Action;
import com.derby.dms.domain.User;
import com.derby.dms.util.Constant;
import java.util.Map;
/*
要开发自己的拦截器类,必须实现com.opensympony.xwork2.interceptor.Interceptor接口,该接口必须
要实现三个方法 void destory() void init() String intercept(ActionInvocation invocation) throws Exception
init(): 在该拦截器被执行之前,系统将回调此方法,此方法只执行一次。因此,该方法的方法体主要用于打开一次性资源
例如:数据库连接等。 ,
destory(): 在该拦截器被销毁之前,系统将回调此方法。该方法用于销毁在init()方法里打开的资源。
intercept(ActionInvocation invocation) : 该方法是用户需要实现的拦截动作,就像Action的execute方法一样,
intercept会返回一个字符串作为逻辑视图。ActionInvocation参数包含了被拦截的Action的引用,可以通过调用
该参数的invoke方法,将控制权转给下一个拦截器,或者转给Action的execute方法。
struts2 还提供了一个AbstractInterceptor类,该类提供了一个init和destory方法的空实现,如果我们实现的拦截器
不需要申请资源,则可以无需实现这两个方法。继承该类就可以了
public class SimpleInterceptor implements Interceptor {
public void init() {
}
public void destroy() {
}
public String intercept(ActionInvocation actionInvocation) throws Exception {
return null;
}
}
public class SimpleInterceptor extends AbstractInterceptor {
private String name;
public String intercept(ActionInvocation actionInvocation) throws Exception {
Map session = ActionContext.getContext().getSession();
User user = (User) session.get(Constant.USER);
if (user == null) {
return Action.LOGIN;
}
//执行该拦截器的后一个拦截器,或者直接指定Action的execute方法
return actionInvocation.invoke();
}
public void setName(String name) {
this.name = name;
}
}