tags:

views:

207

answers:

2

i want code to check whether the user in logged in or not. i want code for servlets.

Thanks in advance

A: 

HttpServletRequest.getUserPrincipal()

david a.
thanks yes i can work. But tell me how i can set the usename in servlet so that it is further called by getUserPrincipal()
satya
You can't set the principal in a J2EE app. App server has to that instead.Your app only has to provide definitions of security rules and its assignments to servlets, app server does the rest (i.e. identifying a user and authorizing them to access particular endpoint.There are many tutorials regarding J2EE security, e.g. one here: http://java.sun.com/javaee/5/docs/tutorial/doc/bncbx.html
david a.
A: 

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.

BalusC