i want code to check whether the user in logged in or not. i want code for servlets.
Thanks in advance
i want code to check whether the user in logged in or not. i want code for servlets.
Thanks in advance
The HttpServletRequest#getUserPrincipal()
only applies when you make use of Java EE provided container managed security as outlined here.
If you want to homegrow your own security, then you need to rely on the HttpSession
. It's not that hard, here is an overview what you need to implement on each step:
On login, get the User
from the DB and store it in session:
User user = userDAO.find(username, password);
if (user != null) {
session.setAttribute("user", user);
} else {
// Show error like "Login failed, unknown user, try again.".
}
On logout, just remove the User
from the session or -more drastically- invalidate the entire session.
session.removeAttribute("user");
// or
session.setAttribute("user", null);
// or
session.invalidate();
To check if an User
is logged in or not, create a Filter
class which is mapped with an url-pattern
which covers the restricted pages, e.g. /secured/*
, /protected/*
, etcetera and implement doFilter()
like follows:
if (session.getAttribute("user") == null) {
response.sendRedirect("login"); // Not logged in, redirect to login page.
} else {
chain.doFilter(request, response); // Logged in, just continue chain.
}
That's basically all.