O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

15.5. Logging Out a User

Problem

You want to log out a user in a system that uses form-based authentication.

Solution

Call invalidate( ) on the user's HttpSession object.

Discussion

Invalidating a user's HttpSession object will log the user out in an application that uses form-based authentication. Naturally, this code involves calling HttpSession.invalidate( ). Example 15-8 displays some information about a logged-in user, then logs him out by invalidating his session. The next time this user requests a protected resource, the web application will send him to the configured login page, because he has been logged out of the application.

Example 15-8. Logging out a user

package com.jspservletcookbook;           

import javax.servlet.*;
import javax.servlet.http.*;

public class LogoutServlet extends HttpServlet {

  public void doGet(HttpServletRequest request, 
    HttpServletResponse response)throws ServletException, 
      java.io.IOException {
    
       HttpSession session = request.getSession( );
       response.setContentType("text/html");
       java.io.PrintWriter out = response.getWriter( );
       out.println(
       "<html><head><title>Authenticated User Info</title></head><body>");
           out.println("<h2>Logging out a user</h2>");
       out.println("request.getRemoteUser( ) returns: ");//get the logged-in user's name String remUser = request.getRemoteUser( ); //Is the request.getRemoteUser( ) return value null? If //so, then the user is not authenticated out.println(remUser == null ? "Not authenticated." : remUser ); out.println("<br>"); out.println("request.isUserInRole(\"dbadmin\") ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required