October 3rd, 2013 by Lincoln Baxter III

Create a dynamic Logout URL without a Servlet or JSP, using Rewrite

The code below implements a simple command mapping that binds logout functionality to a URL. To use this example, you must include the following [[Rewrite]] dependency in your project:

<dependency>
   <groupId>org.ocpsoft.rewrite</groupId>
   <artifactId>rewrite-servlet</artifactId>
   <version>${rewrite.version}</version>
</dependency>

Once your project is set up to include Rewrite, just paste the following code into your application source folder.

@RewriteConfiguration
public class LogoutConfiguration extends HttpConfigurationProvider
{

   @Override
   public Configuration getConfiguration(ServletContext context)
   {
      return ConfigurationBuilder.begin()
               .addRule()
               .when(Direction.isInbound().and(Path.matches("/logout")))
               .perform(new HttpOperation() {
                  @Override
                  public void performHttp(HttpServletRewrite event, EvaluationContext context)
                  {
                     event.getRequest().getSession().invalidate();
                  }
               }.and(Redirect.temporary(context.getContextPath() + "/")));
   }

   @Override
   public int priority()
   {
      return Integer.MIN_VALUE;
   }
}