使用MethodFilterInterceptor 自定义方法过滤拦截器,然后:
在struts.xml配置文件中,找到interceptor-ref 标签,添加:
edit,add
自定义拦截器:
package net.hncu.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class MyInterceptor3 extends MethodFilterInterceptor{
//拦截器的名称
private String interceptorName;
public void setInterceptorName(String interceptorName) {
this.interceptorName = interceptorName;
}
//实现拦截的方法
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println(interceptorName + ":-----2拦截前操作-----");
String result = invocation.invoke();
System.out.println(interceptorName + ":------2拦截后操作------");
return result;
}
}
给一个struts.xml文件你参考:
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
过滤拦截器
自定义过滤拦截器
edit,add
1.继承类MethodFilterInterceptor(此类是类AbstractInterceptor的子类)
import java.util.Map;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
/*
*拦截指定方法
*/
public class MyFilterInterceptor extends MethodFilterInterceptor{
private static final long serialVersionUID = 1L;
private String name;
public void setName(String name)
{
this.name = name;
}
@Override
protected String doIntercept(ActionInvocation invocation) throws Exception {
//取得请求相关的ActionContext实例
ActionContext ctx = invocation.getInvocationContext();
Map session = ctx.getSession();
//取出名为user的Session属性
String user = (String)session.get("user");
//如果没有登陆,或者登陆所用的用户名不是scott,都返回重新登陆
if (user != null && user.equals("scott") )
{
return invocation.invoke();
}
//没有登陆,将服务器提示设置成一个HttpServletRequest属性
ctx.put("tip" , "您还没有登陆,请输入scott,tiger登陆系统");
//直接返回login的逻辑视图
return Action.LOGIN;
}
}
2.struts.xml配置
getALL,getPart,listUser
1)创建继承MethodFilterInterceptor的方法拦截器,并在配置时把你要拦截的方法加入到includeMethods结点中,可参造liangjian103的回答
2)至于你所说只想拦截某些action,如果你不是采用通配符的方式,即你是有几个action类就要在struts.xml中配置几个action结点的话,那就简单,哪些action要拦截,就在那些action下面引用这个拦截器,写法类似yingjianxuehun 的回答 。
如果你是采用通配符的方式,即struts.xml中只有一个action结点的话,那便在拦截器中对action进行滤,获取到请求的路径后对路径进行判断
可以的。在你struts.xml里面的action标签内,增加method方法。比如:method="edit"或method="add"。如果不加的话,它就默认执行execute()方法。
在配置文件里面设置:
你要拦截的方法