当前位置: 代码迷 >> Web前端 >> struts2中应用自定拦截器
  详细解决方案

struts2中应用自定拦截器

热度:103   发布时间:2012-08-21 13:00:21.0
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; } } 
?

?


?在配置文件中配置:

1 楼 lihengzkj 2011-10-25  
编辑过程中出现了错误,谅解!拦截器的代码在最下面。
  相关解决方案