Few to  tutorials ago - in  Authenticate and Authorize users with Servlets/JSPs and Hibernate - we saw how to implement an authentication controller.In this tutorial we will see a simple way to implement a logout controller.


package com.javaonly.controllers.readControllers;


package com.javaonly.controllers.readControllers;

import com.javaonly.Daos.DaoFactory;
import com.javaonly.Daos.UserDao;
import com.javaonly.hibernate.HibernateUtil;
import com.javaonly.model.Users;

public class LogoutController extends ReadController {

    public void execute() {
        String username = (String) this.getRequest().getSession().getAttribute("username");
        UserDao userDao = DaoFactory.getUserDao();
        HibernateUtil.beginViewTransaction();
        if (username != null) {
            Users user = userDao.getUserByUserName(username);
            HibernateUtil.commitTransaction();
            if (user != null) {
                this.getRequest().getSession().removeAttribute("username");
                this.getRequest().getSession().removeAttribute("role");
                this.setReturnPage("/index.jsp");
            } else {
                this.setReturnPage("/login.jsp");
            }
        } else {
            this.setReturnPage("/login.jsp");
        }
    }
}

 As you can see in the above snippet all we had to do was to remove from session the username and the role attributes that were set when user logged in and redirect the request  to the index page of the application