struts1攔截器

Struts2已經發布一段時間了,這個版本較struts1.x版本有了很大變化,其中一個就是增長了攔截器功能。這是個很是有用的功能,但是struts1.x卻沒有。     其實,struts1.x能夠配合插件,實現攔截器的功能。     SAIF(Struts Action Invocation Framework)是一個開源組件,它讓Struts框架具有Action攔截器與IOC的功能,這樣你的1.x框架也就有了攔截器的功能。       1.將saif.jar包放入你的lib中。       2.建立Interceptor類。好比我在這裏建立一個類:java

package interceptor;
import java.io.IOException;
import javax.servlet.ServletException;
   import javax.servlet.http.HttpServletRequest;
   import javax.servlet.http.HttpServletResponse; 
import org.apache.struts.action.Action;
   import org.apache.struts.action.ActionForm;
   import org.apache.struts.action.ActionForward;
   import org.apache.struts.action.ActionMapping;
import net.sf.struts.saif.ActionHaveForwardInterceptor;
public class Display Interceptor implements ActionHaveForwardInterceptor{     
        public ActionForward afterAction(Action arg0, ActionMapping arg1,             
             ActionForm arg2, HttpServletRequest arg3, HttpServletResponse arg4)            
                 throws IOException, ServletException{         
                    // TODO Auto-generated method stub         
                            returnnull;     
                        }     
               public ActionForward beforeAction(Action action, ActionMapping mapping,              ActionForm form, HttpServletRequest request, HttpServletResponse response)             throws IOException, ServletException{         
            // TODO Auto-generated method stub         
                  System.out.println("Inteceptor...");        
                            if (!"fred".equals(request.getParameter("user_name"))){             
                                return mapping.findForward("noPermission");         
                                      }         
                                 returnnull;     
                                   } 
}

3.寫interceptor配置文件:interceptor-config.xml。這個配置文件中指定了interceptor類和要被攔截的actionapache

<?xml version="1.0" encoding="UTF-8"?>
<interceptor-config>   
<interceptorname="displayInterceptor" type="interceptor.DisplayInterceptor"/>        
<actiontype="/display">         
<interceptorname="displayInterceptor"/>   
</action>      </interceptor-config>

4.在struts-config.xml中指定加載interceptor-config.xml服務器

<plug-in className="net.sf.struts.saif.SAIFSpringPlugin">     
<set-propertyproperty="interceptor-config" value="/WEB-INF/interceptor-config.xml"/>   
</plug-in>

ok,配置完後,啓動服務器,而後輸入.../display.do?user_name=fred,回車,這時候,這個請求就會被攔截來,app

進入beforeAction中,進行驗證,若驗證成功,return null,就會轉到action的forward指向的頁面,若不成功,框架

就會轉向另外一個頁面。spa

相關文章
相關標籤/搜索