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.