使用攔截器來檢測使用者是否登入

來源:互聯網
上載者:User

在任何一個系統中,都會有登入介面,因為只有通過驗證的使用者才能訪問網路上的資源,在桌應用程式中,系統的入口就只有一個,那就是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>

這樣如果使用者請求登入頁面,可以順利通過,如果使用者請求其他頁面,就需要檢查使用者是否已經登入,如果沒有登入,則跳回登入頁面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.