struts2中使用自定拦截器

struts2中实现自定义的拦截器,有三种方式:

    1、实现interceptor接口

    2、继承AbstractInterceptor这个抽象类

    3、继承MethodFilterInteceptor类

 

这里我只用了第一种方式:

 

<interceptors > <interceptor name="InterceptorOne" class="com.nce.interceptor.MyInterceptorOne"></interceptor> </interceptors>

 

 

 在*Action的配置文件中加入:这里使用loginAction

<action name="login" class="com.ncs.action.LoginAction"> <result name="success">Success.jsp</result> <result name="failure">Failure.jsp</result> <interceptor-ref name="InterceptorOne"></interceptor-ref> </action>

 

 

 接下来就可以运行了,如果你的请求中有你输入的参数的话,那么你会在页面中看到这样的错:500;                java.lang.NullPointerException

这是为什么呢?通过实现,我觉得在我们使用了自定义的拦截器以后,那么struts2默认的拦截器就没有使用了,而默认的拦截器就有把请求流中的值注入到属性中的功能,而我们自定义的拦截器是没有这个功能的,那么自然就要报空指针的错误了。那么最有效的方法就是在我们使用自定义的拦截器的同时也使用默认的拦截器。方法如下:

(一)在interceptors中加入:

 

<interceptors > <interceptor name="InterceptorOne" class="com.nce.interceptor.MyInterceptorOne"></interceptor> <interceptor-stack name="myStack"> <interceptor-ref name="InterceptorOne"></interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> </interceptors>

 

 

 而在loginAction的配置中使用myStack

<action name="login" class="com.ncs.action.LoginAction"> <result name="success">Success.jsp</result> <result name="failure">Failure.jsp</result> <interceptor-ref name="myStack"></interceptor-ref> </action>

 

 

 

(二)直接将默认的拦截器放入loginAction的配置中

<action name="login" class="com.ncs.action.LoginAction"> <result name="success">Success.jsp</result> <result name="failure">Failure.jsp</result> <interceptor-ref name="InterceptorOne"></interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </action>

 

 

 
 这样就可以避免很多错误了。

 

 

 

 
import com.opensymphony.xwork2.ActionInvocation; 
import com.opensymphony.xwork2.interceptor.Interceptor;
 public class MyInterceptorOne implements Interceptor{ 
public void destroy() { // TODO Auto-generated method stub } 
public void init() { // TODO Auto-generated method stub } 
public String intercept(ActionInvocation invocation) throws Exception {
 // TODO Auto-generated method stub 
System.out.println("begin to intercept..."); 
String result = invocation.invoke(); 
System.out.println("end to intercept..."); 
return result; } } 
 

 


 在配置文件中配置:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值