现在的位置: 首页 > 综合 > 正文

Struts2自定义拦截器

2013年10月24日 ⁄ 综合 ⁄ 共 2311字 ⁄ 字号 评论关闭
文章目录

 

拦截器是用来动态拦截Action调用的对象,允许在一个Action执行前阻止其执行。

 

自定义一个拦截器类需要实现com.opensymphony.xwork2.interceptor.Interceptor接口:

第一步:新建一个继承com.opensymphony.xwork2.interceptor.Interceptor的拦截器类,如上图

 LoginInterceptor.java

 public class LoginInterceptor implements Interceptor {

 public void destroy() {
    // TODO Auto-generated method stub

 }

 public void init() {
   // TODO Auto-generated method stub
 }

 public String intercept(ActionInvocation arg0) throws Exception {
   // TODO Auto-generated method stub

    <!-- 判断用户是否已登录  -->
         if(ActionContext.getContext().getSession().get("user")!=null)
        {

              <!-- 继续执行action中内容  -->
              return arg0.invoke();
         }else
         {

              <!-- 直接退出action,并返回error-->
             ActionContext.getContext().getSession().put("message", "用户未登录");
             return "error";
         }
    }

 }

 

第二步:配置自定义拦截器:

Struts.xml

  <package name="loginpackage" namespace="/test1" extends="struts-default">

        <!-- 定义一个拦截器 -->
       <interceptors>

             <!-- 自定义拦截器 -->
             <interceptor name="test" class="action.LoginInterceptor"></interceptor>

             <!-- 定义一个拦截器栈-->
             <interceptor-stack name="testStack">

                    <!--  定义系统核心拦截器,放在自定义拦截器前面,以避免核心拦截器被自定义拦截器覆盖-->
                   <interceptor-ref name="defaultStack"></interceptor-ref>
                   <interceptor-ref name="test"/>
            </interceptor-stack> 
     </interceptors>
    <action name="action1_*" class="action.LoginAction" method="{1}">

          <!-- 只对action1_*起作用,可以定义默认拦截器来对所有action都有效-->
          <interceptor-ref name="testStack"/> 
          <result>/MyJsp.jsp</result>
          <result name="error">/error.jsp</result>
    </action> 
  </package>

提醒:默认拦截器定义:<default-interceptor-ref name="testStack"/>,可以作用于所有的action。

           但当某个action中也配置了拦截器,默认拦截器将不会在该action中实现。

 

LoginAction.java

   public class LoginAction extends  ActionSupport{
 
   public String login()
   {
          ActionContext.getContext().getSession().put("message", "用户已登录");
          return "success";
   }

   }

 

MyJSP.jsp

 <body>     
       <%=request.getSession().getAttribute("message") %> <br>
  </body>

 

index.jsp

    <% request.getSession().setAttribute("user", "zhangsan"); %>

 

功能实现:用户未登录时(session中user值为空)在跳转到主页面时拦截器会自动进行拦截。

测试:

   http://localhost:8080/interceptor/test1/action1_login.action   结果:用户未登录

1.http://localhost:8080/interceptor/index.jsp

2.http://localhost:8080/interceptor/test1/action1_login.action   结果:用户已登录

 

 

抱歉!评论已关闭.