一、Interceptor类创建
这里有一点需要注意:如果放行了,就不会再执行最后return的结果了,参考论坛讨论:
https://bbs.csdn.net/topics/370194837 12楼的回答:
楼上是正解,这是struts2的机制,只要调用 invoke()方法后,如果能成功的调用了对应Action类中的方法,strtus2就会按照该方法的返回值去找对应的result,从而忽略拦截器的返回值;如果你不调用invoke()方法,那么页面就会跳转到你在拦截器中指定的result对应的页面。这个方式通常用于权限验证,当符合权限要求的时候才会调用invoke()方法,执行Action类中的方法;不满足权限的调价直接返回错误页面,这是就用到了拦截器中的返回值了。
package com.aitiman.demo;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
@SuppressWarnings("serial")
public class MyInterceptor extends MethodFilterInterceptor {
@Override
protected String doIntercept(ActionInvocation invocation) throws Exception {
System.out.println("前处理");
//放行
invocation.invoke();
System.out.println("后处理");
return "to2JSP";//不放行,跳转到结果
}
}
二、struts.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="dev-mode" value="true"></constant>
<package name="demo" namespace="/" extends="struts-default">
<!-- 配置拦截器 -->
<interceptors>
<!-- 注册拦截器 -->
<interceptor name="MyInterceptor" class="com.aitiman.demo.MyInterceptor"></interceptor>
<!-- 配置拦截器栈 -->
<interceptor-stack name="myStack">
<interceptor-ref name="MyInterceptor">
<!-- 指定哪些方法不拦截 -->
<param name="excludeMethods">fun1,fun2</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 指定包的默认拦截器栈 -->
<default-interceptor-ref name="myStack"></default-interceptor-ref>
<global-results >
<result name="to2JSP" type="redirect">/2.jsp</result>
</global-results>
<action name="DemoAction_*" class="com.aitiman.demo.DemoAction" method="{1}">
<!-- 为Action指定拦截器栈 -->
<!-- <interceptor-ref name="myStack"></interceptor-ref> -->
<result name="success" type="redirect">/1.jsp</result>
</action>
</package>
</struts>
三,编写Action类进行测试
package com.aitiman.demo;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class DemoAction extends ActionSupport {
public String fun1() throws Exception {
System.out.println("fun1 is working1");
return "success";
}
public String fun2() throws Exception {
System.out.println("fun2 is working!");
return "success";
}
public String fun3() throws Exception {
System.out.println("fun3 is working!");
return "success";
}
public String fun4() throws Exception {
System.out.println("fun4 is working!");
return "success";
}
}
四,测试,分别访问:
http://localhost:8080/项目名/DemoAction_fun1
http://localhost:8080/项目名/DemoAction_fun2
http://localhost:8080/项目名/DemoAction_fun3
http://localhost:8080/项目名/DemoAction_fun4
http://localhost:8080/项目名/DemoAction_fun5