轉自博客:http://blog.csdn.net/pkgk2013/article/details/51985817
攔截器的作用
攔截器,在AOP(Aspect-Oriented Programming)中用於在某個方法或字段被訪問之前,進行攔截然后在之前或之后加入某些操作。攔截是AOP的一種實現策略。 攔截器是動態攔截Action調用的對象。它提供了一種機制可以使開發者可以定義在一個action執行的前后執行的代碼,也可以在一個action執行前阻止其執行。同時也是提供了一種可以提取action中可重用的部分的方式。
自定義攔截器
有的時候struts2提供的攔截器並不能滿足我們的需求,所以我們會選擇自定義攔截器。就以商城系統中,后台的數據管理為例,如果沒有登錄,就不能訪問一系列后台的頁面。
- 編寫攔截器:
- 編寫一個類實現Interceptor接口.或者繼承Interceptor的子類.
- 配置攔截器.
public class PrivilegeInterceptor extends MethodFilterInterceptor{ @Override protected String doIntercept(ActionInvocation actionInvocation) throws Exception { // 判斷是否登錄,如果登錄,放行,沒有登錄,跳轉到登錄頁面. AdminUser adminUser = (AdminUser) ServletActionContext.getRequest() .getSession().getAttribute("existAdminUser"); if(adminUser != null){ // 已經登錄過 return actionInvocation.invoke(); }else{ // 跳轉到登錄頁面: ActionSupport support = (ActionSupport) actionInvocation.getAction(); support.addActionError("您還沒有登錄!沒有權限訪問!"); return ActionSupport.LOGIN; } } }
在struts.xml中進行配置
<!-- 配置自定義攔截器 --> <interceptors> <interceptor name="privilegeInterceptor" class="com.wgd.shop.interceptor.PrivilegeInterceptor"/> </interceptors> //在這里,我們為了圖方便,就直接寫的是全局的訪問 <global-results> <result name="msg">/WEB-INF/jsp/msg.jsp</result> <result name="login">/admin/index.jsp</result> </global-results> //在相應的action中配置該攔截器 <!-- 后台一級分類管理Action --> <action name="adminCategory_*" class="adminCategoryAction" method="{1}"> <result name="findAll">/admin/category/list.jsp</result> <result name="saveSuccess" type="redirectAction">adminCategory_findAll</result> <result name="deleteSuccess" type="redirectAction">adminCategory_findAll</result> <result name="editSuccess">/admin/category/edit.jsp</result> <result name="updateSuccess" type="redirectAction">adminCategory_findAll</result> <interceptor-ref name="privilegeInterceptor"/> <interceptor-ref name="defaultStack"/> </action> //因為配置了自定義攔截器,默認的攔截器就沒有了。所以得手動添加默認的攔截器