`

srtuts2的拦截器(interceptor)

阅读更多

1. 自定义的拦截器
   第一步:编写自定义的拦截器类,该类实现import
com.opensymphony.xwork2.interceptor.Interceptor;接口
   
  //下面模拟用户登录 
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class PermissionInterceptor implements Interceptor {

	public void destroy() {
		System.out.println("======PermissionInterceptor=====destroy============");
	}

	public void init() {
		System.out.println("====PermissionInterceptor===init================");
	}

	public String intercept(ActionInvocation invocation) throws Exception {
		Object user = ActionContext.getContext().getSession().get("user");
		if(user!=null) return invocation.invoke(); //如果user不为null,代表用户已经登录,允许执行action中的方法
		ActionContext.getContext().put("message", "你没有权限执行该操作");
		return "success";
	}
}


第二步:在struts.xml中配置拦截器
 <struts>
  	<package name="employee" namespace="/control/employee" extends="struts-default">
		<interceptors> //配置拦截器组
			<interceptor name="permission" class="cn.itcast.interceptor.PermissionInterceptor"/>
			<interceptor-stack name="permissionStack">  //配置拦截器栈
				<interceptor-ref name="defaultStack"/>
				<interceptor-ref name="permission" />
			</interceptor-stack>
		</interceptors>
		<global-results>
			<result name="success">/WEB-INF/page/message.jsp</result>
		</global-results>
		<action name="list_*" class="cn.itcast.action.HelloWorldAction" method="{1}">
			<interceptor-ref name="permissionStack" />  //把拦截器添加到具体的某个action中
		</action>
	</package>
</struts>


注意:在action上添加拦截器时,action本身有一系列的struts2的拦截器,所以要先保留action本身的拦截器,
      再添加自定义的拦截器,具体做法,就是定义一个拦截器栈interceptor-stack,在栈中先保留defaultStack拦截器
      再添加自定义的拦截器,且要把defaultStack拦截器放在最前面,应为是按执行顺序来调用拦截器的
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics