Monday, December 6, 2010

Switching Login Page in Activity

In GWT with MVP, how to switch member pages to default login page when session was invalid?
A simple way is to use the goTo method of PlaceController.


public class MemberActivity extends AbstractActivity implements MemberView.Presenter {
    private final ClientFactory clientFactory;
    private MemberView view;
    private static String sid;
    public MemberActivity(ClientFactory factory){
        clientFactory = factory;
    }
    @Override
    public void start(final AcceptsOneWidget panel, EventBus eventBus) {
        sid = Cookies.getCookie("sid");
        if (clientFactory.getMemberService().validSession(sid, new AsyncCallback<Boolean>(){
            @Override
            public void onFailure(Throwable caught) {
                clientFactory.getPlaceController().goTo(new LoginPlace());
            }
            @Override
            public void onSuccess(CmmsAccountDto result) {
                if (!result){
                    clientFactory.getPlaceController().goTo(new LoginPlace());
                    return;
                }

                view = clientFactory.getMemberView();
                view.setPresenter(this);
                panel.setWidget(view);
            }
        });
    }
}

But, this way have a problem that browser history is increased.
The browser cannot return to the history before MemberPlace with the back button because the browser redirects to LoginPlace when it visits MemberPlace.

Then, I used the approach that called another Activity from a Activity.


public class MemberActivity extends AbstractActivity implements MemberView.Presenter {
    private final ClientFactory clientFactory;
    private MemberView view;
    private static String sid;
    public MemberActivity(ClientFactory factory){
        clientFactory = factory;
    }
    @Override
    public void start(final AcceptsOneWidget panel, final EventBus eventBus) {
        sid = Cookies.getCookie("sid");
        if (clientFactory.getMemberService().validSession(sid, new AsyncCallback<Boolean>(){
            @Override
            public void onFailure(Throwable caught) {
                loginView(panel, eventBus);
            }
            @Override
            public void onSuccess(CmmsAccountDto result) {
                if (!result){
                    loginView(panel, eventBus);
                    return;
                }

                view = clientFactory.getMemberView();
                view.setPresenter(this);
                panel.setWidget(view);
            }
        });
    }

    private void loginView(AcceptsOneWidget panel, EventBus eventBus){
        LoginActivity loginActivity = new LoginActivity(clientFactory);
        loginActivity.start(panel, eventBus);
    }
}

In above code, The view can be switched without the history changing.