When not taking benefit of the Java EE provided container managed security, then the normal basic practice is that you store the logged-in User
in the session scope and uses a Filter
on the desired url-pattern
to check if the User
is logged in.
Here's a basic example to get the picture:
Login:
User user = userDAO.find(username, password);
if (user != null) {
session.setAttribute("user", user);
} else {
// Do your thing to show "Unknown login" error.
}
Filter (which is mapped on an url-pattern of for example /secured/*
, /protected/*
, etc where in you place the restricted JSP pages expect of the login page):
User user = session.getAttribute("user");
if (user != null) {
chain.doFilter(request, response); // Logged in, so continue with request.
} else {
response.sendRedirect("login"); // Not logged in, redirect to login page.
}
Logout:
session.removeAttribute("user");
// Or, a bit too drastically:
session.invalidate();
You can of course also take benefit of what Java EE out of the box provides with regard to security. A commonly used way is the declarative container managed security wherein you can specify users and roles. You just need to declare a <security-constraint>
and a <login-config>
in the web.xml
and configure an user realm in the appserver. The details depends on the appserver used, but if it is for example Tomcat 6.0, then you can find here some documentation about that.