Logout with confirmation dialog

A question on OTN (http://forums.oracle.com/forums/forum.jspa?forumID=83) leads to this short article.

The use case requires to ask for a confirmation before logging out of the application.  This can easily implemented using a OK/Cancel dialog  which we show on a button click.

My simple test page looks like this:

On a click on the logout button we show a confirmation dialog as popup:

The dialog uses a dialog listener to catch the user input.  For an OK/Cancel dialog only the click on the OK button is passed to the listener. Closing the dialog or clicking cancel never calls the dialog listener. Clicking on OK navigates to a logout page:

Looks pretty simple,  still we need  a few things to mention. The code for the logout button and popup  looks like:

<af:panelGroupLayout id="pgl1">
  <af:commandButton text="Logout" id="cb2">
    <af:showPopupBehavior popupId="p1" triggerType="action"/>
  </af:commandButton>
  <af:popup id="p1">
    <af:dialog id="d2" dialogListener="#{LoginLogout.dialogLogoutListener}" title="Confirmation">
    <af:outputText value="Do you want to logout?" id="ot2"/>
    </af:dialog>
  </af:popup>
 </af:panelGroupLayout>

The real work is done in the dialog listener in the managed bean (here called LoginLogout). The dialog listener checks if OK was clicked, and then calls the logoutTarget method with a parameter which is the target page after invalidating the session. This page is a normal html page just showing the user that his session has ended. On this page you can put a link back to the application as shown above.

public String logoutTarget(String aTarget)
{
  ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
  HttpServletResponse response = (HttpServletResponse) ectx.getResponse();
  String url = ectx.getRequestContextPath() + aTarget;
  HttpSession session = (HttpSession) ectx.getSession(false);
  //close session
  session.invalidate();
  try
  {
    response.sendRedirect(url);
    FacesContext.getCurrentInstance().responseComplete();
  }
  catch (IOException e)
  {
    e.printStackTrace();
  }
  return null;
}

public void dialogLogoutListener(DialogEvent dialogEvent)
{
  if (dialogEvent.getOutcome() == DialogEvent.Outcome.ok)
  {
    logoutTarget("/ByBy.html");
  }
}

If you use a jspx page which is part of  your application, the session gets invalidated but you see that url rewriting stuff is still part of the url you see in the browser.

http://127.0.0.1:7101/LoginLogout/faces/Logout.jspx?_afrWindowMode=0&_afrLoop=10962072683890&_adf.ctrl-state=10eyn0547w_4

I like it if the url looks like

http://127.0.0.1:7101/LoginLogout/ByBy.html

so I use a normal html page.

Feel free to play with this. You only have to change the parameter in the logoutTarget(…) method call to

logoutTarget("/faces/Logout");

if you have a page Logout.jspx in your application.

Advertisements