Struts2之自定义拦截器和配置

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011301372/article/details/85055675

编写拦截器,需要实现Interceptor接口,实现接口中的三个方法

  • interceptor接口有很多的实现类,编写最简单的方式就是继承AbstractInterceptor实现类
  • 代码如下
public String intercept(ActionInvocation invocation) throws Exception{
	User user = (User) ServletActionContext.getRequest().getSession().getAttribute("existUser");
	if(user==null){
	}else{
		return invocation.invoke();
	}
}

在struts.xml中配置拦截器

第一种方式

  • <package>包中定义拦截器,出现在<package>包的上方
<interceptors>
	<invercrptor name="loginInterceptor" class="com.zst.interceptor"></interceptor>
</interceptor>

在某个action中引入拦截器

  • <intercepor-ref name="loginInterceptor"></interceptor-ref>
  • 注意:如果引入了自己定义的拦截器,那么struts2框架默认的拦截器就不会再执行了,所有需要引入Struts2默认的拦截器
  • <interceptor-ref name="defaultStack"></interceptor-ref>
public class UserAction extends ActionSupport {
    public String execute()throws Exception{
        System.out.println("intercept拦截器");
        return NONE;
    }
}
public class DemoInterceptor extends AbstractInterceptor{
    //intercept 用来进行拦截
    public String intercept(ActionInvocation invocation) throws Exception{
        System.out.println("Action方法执行前,,,");
        //执行下一个拦截器
       String result = invocation.invoke();
       // invocation.invoke();

        System.out.println("Action的方法 执行之后,,,");
        return result;
    }
}
<package name="demo3" extends="struts-default" namespace="/">
        <interceptors>
            <!--定义了拦截器,名称可以任意起,一般用类的名称-->
            <interceptor name="DemoInterceptor" class="com.zst.interceptor.DemoInterceptor"/>
        </interceptors>


        <action name="userAction" class="com.zst.demo3.UserAction">
            <!--只要引用了自己的拦截器,默认栈的拦截器就不执行了,必须要手动引入默认栈-->
            <interceptor-ref name="DemoInterceptor"/>
            <!--手动引入默认栈,在struts-default.xml中查找interceptor-stack name="defaultStack"-->
            <interceptor-ref name="defaultStack"/>
        </action>

    </package>

第二种方式

<package>包中定义拦截器的时候,自己直接定义一个拦截器

<interceptors>
	<interceptor name="loginInterceptor" class="com.zst.interceptor.LoginInterceptor"/>
	<interceptor-stack name="myStack">
		<interceptor-ref name="loginInterceptor"/>
		<interceptor-ref name="defaultStack"/>
	</interceptor-stack>
</interceptors>

在Action包中引入自己定义的拦截器栈

<action name = "book_*" class="com.zst.action.BookAction" method="{1}">
	<interceptor-ref name="myStack"/>
</action>

猜你喜欢

转载自blog.csdn.net/u011301372/article/details/85055675