在任何一個系統中,都會有登入介面,因為只有通過驗證的使用者才能訪問網路上的資源,在桌應用程式中,系統的入口就只有一個,那就是main函數,但是在b/s這種結構中,我們可以向伺服器請求任何一個頁面,也就是說有多個入口,那麼我們如何限制使用者只能通過登入這個介面進入系統呢,實現的方法有很多,現在介紹一種比較常用的方法,使用structs2中的攔截器:
首先我們定義一個攔截器:
public class MyInterceptor implements Interceptor{public void destroy(){// TODO Auto-generated method stubSystem.out.println("攔截器銷毀!");}public void init(){// TODO Auto-generated method stubSystem.out.println("攔截器初始化");}public String intercept(ActionInvocation invocation) throws Exception{// TODO Auto-generated method stubSystem.out.println("攔截器開始驗證!");if(LoginAction.class==invocation.getAction().getClass()){return invocation.invoke();}User user=(User)invocation.getInvocationContext().getSession().get("user");if(user==null)return "fail";System.out.println("使用者已經登入");return invocation.invoke();}}
然後在struts.xml中配置攔截器
<interceptors> <interceptor name="login" class="com.interceptor.MyInterceptor"></interceptor> <interceptor-stack name="mystack"> <interceptor-ref name="login"></interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> </interceptors> <default-interceptor-ref name="mystack"></default-interceptor-ref>
這樣如果使用者請求登入頁面,可以順利通過,如果使用者請求其他頁面,就需要檢查使用者是否已經登入,如果沒有登入,則跳回登入頁面