java拦截器继承类_struts2的拦截器(5):继承MethodFilterInterceptor抽象类实现拦截方法的拦截器 | 学步园...

在默认情况下,如果我们为某个Action定义了拦截器,则这个拦截器会拦截该Action内的所有方法。但在某些情况下,我们不想拦截所有的方法,我们只需要拦截某些特定方法,此时就需要使用struts2拦截器的方法过滤特性。

为了实现方法过滤的特性,struts2提供了一个MethodFilterInterceptor抽象类,它是AbstractInterceptor的子类,如果用户需要自定义的拦截器支持方法过滤特性,应该继承MethodFilterInterceptor,并重写doIntercept(ActionInvocation invocation)方法。

9378c70a6b1f71005107e47be352f117.png

index.jsp :

Insert title here

function register(){

var targetForm=document.forms[0];

targetForm.action="register";

}

function login(){

var targetForm=document.forms[0];

targetForm.action="login";

}

welcome.jsp :

Insert title here

Object 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";

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值