0

I created a Registration form using HTML and add a sign In page also in HTML. I need to display the username on the top of the series of pages once i login. I have already know how to do that in PHP, but i want to know whether i can do it with JSP or not. If i can do it, how to do that.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
sapan
  • 259
  • 3
  • 6
  • 16

1 Answers1

2

Assumming the user has been successfully validated and authenticated into the system in your servlet (or another controller), then just save the User object in session and then retrieve it where you need it. A basic example:

In your servlet:

public void doPost(HttpServletRequest request, HttpServletResponse response) {
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    User user = new UserService().login(username, password);
    if (user != null) {
        //success!
        //save the user data in session scope
        HttpSession session = request.getSession();
        session.setAttribute("user", user);
        //do your forward or redirect...
    }
    //do your forward or redirect to show error messages...
}

Then in your JSP code, you can access to user session attribute using Expression Language, never scriptlets (more info on avoid scriptlets usage: How to avoid Java code in JSP files?).

<div id="top">
    <!-- this assumes your User class has a username field with a valid getter -->
    Hello ${user.username}
</div>
Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • Thank you. It's working. and also can you help me how to display a error message(not error page) if a user enters wrong login or password while signIn. – sapan Sep 20 '13 at 22:07
  • @sapan that should be handled in a new Q/A. Anyway, related: http://stackoverflow.com/a/17001503/1065197 – Luiggi Mendoza Sep 20 '13 at 22:16