在默认情况下,如果我们为某个Action定义了拦截器,则这个拦截器会拦截该Action内的所有方法。但在某些情况下,我们不想拦截所有的方法,我们只需要拦截某些特定方法,此时就需要使用struts2拦截器的方法过滤特性。
为了实现方法过滤的特性,struts2提供了一个MethodFilterInterceptor抽象类,它是AbstractInterceptor的子类,如果用户需要自定义的拦截器支持方法过滤特性,应该继承MethodFilterInterceptor,并重写doIntercept(ActionInvocation invocation)方法。
index.jsp :
Insert title herefunction register(){
var targetForm=document.forms[0];
targetForm.action="register";
}
function login(){
var targetForm=document.forms[0];
targetForm.action="login";
}
welcome.jsp :
Insert title hereObject obj=session.getAttribute("name");
if(obj==null){
response.sendRedirect("index.jsp");
}
%>
${tip} success...
struts.xml :
/p>
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
/welcome.jsp
/index.jsp
register
login
SimpleMethodFilterInterceptor.java :
public class SimpleMethodFilterInterceptor extends MethodFilterInterceptor {
@Override
public String doIntercept(ActionInvocation invocation) throws Exception {
System.out.println("Action被拦截之前,当然你可以在这里做点什么...");
String result=invocation.invoke();
System.out.println("Action被拦截之后,当然你可以在这里做点什么...");
return result;
}
}
LoginAndRegisterAction.java :
public class LoginAndRegisterAction extends ActionSupport {
private String name;
private String pass;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String login(){
if(getName().equals("scott")&& getPass().equals("tiger")){
Map session=ActionContext.getContext().getSession();
session.put("name",getName());
session.put("tip","login");
return "success";
}
return "error";
}
public String register(){
if(getName().equals("scott")&& getPass().equals("tiger")){
Map session=ActionContext.getContext().getSession();
session.put("name",getName());
session.put("tip","register");
return "success";
}
return "error";
}
}