Implementing a logout function in Tapestry 5

I’m working on a couple Java projects right now and so I decided to jump in and give Tapestry 5 a try. So far I’m really liking it, although as many have griped with Tapestry in the past, the documentation is minimal.

As you might already be aware, Tapestry 4 had a RestartService that you could use straight from your page via a ServiceLink. I wasn’t able to find anything similar in T5, and a fair bit of Googling yielded no obvious results on how to implement a logout. Finally I found a way to get at the HttpSession, and from there it’s simply a matter of invalidating it.

Here’s the code for your page/component:

<t:actionlink id=”logout”>Logout</t:actionlink>

Here’s the code for your Java class:

import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.RequestGlobals;
import com.yourapp.pages.Index;

public class Border {
  
  @Inject
  private RequestGlobals requestGlobals;
  
  public Object onActionFromLogout() {
    requestGlobals.getHTTPServletRequest().getSession().invalidate();
    return Index.class;
  }
  
}

Hopefully this will save somebody a bit of time.

2 thoughts on “Implementing a logout function in Tapestry 5”

  1. Thanks for the suggestion! I will re-iterate for readers that the session must already exist or else this would cause a null pointer exception:

    public HttpSession getSession(boolean create)

    Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session.

    If create is false and the request has no valid HttpSession, this method returns null.

Leave a Reply

Your email address will not be published. Required fields are marked *