First, I recommend that you do not call FacesContext in EJB, because FacesContext is a "View Layer" element. EJB's goal is Bussines Logic LAyer, and itโs best practice to extract business process logic from a view because you can access the business process logic from many kinds of views.
On how to close a session, I recommend the following:
Create a servlet to implement the doGet method to close the session as follows:
@WebServlet("/logout") public class LogoutServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { HttpSession session= req.getSession(); session.invalidate(); RequestDispatcher rd = req.getRequestDispatcher("/login.xhtml");
Thus, you can add the following link to the html / xhtml page to exit:
<a href="/logout">Logout</a>
If you use JSF, to get the context path to your application, you can use:
<a href="${request.contextPath}/logout">Logout</a>
DISCLAIMER: I assume that you are using Java EE 6. Also I have not tested the code (but I know that it works), if you have some compilation problems, please let me know
source share