Turk
Turk

Reputation: 269

How come I can pull a session attribute in a JSP page but not in a Servlet?

I have a web application that begins with a login page. During the verification of that login a session is created and the ID used to login is saved as an attribute. That ID is then suppose to be displayed in the pages that user navigates to. So far I can only get it to display in a JSP page but everything I try in a Servlet page does not work.

Here is the logic I used in my login verification page:

UserBean2 userBean2 = (UserBean2) session.getAttribute("userBean2");
String un = request.getParameter("id");
userBean2 = new UserBean2(un);
session.setAttribute("userBean2", userBean2);

Here is the Bean I created UserBean2:

public class UserBean2 {
     private String id;

public UserBean2(String id) {
     setUsername(id);
}

public String getUsername() {
     return(id);
}

public void setUsername(String id) {
     if (!isMissing(id)) {
          this.id = id;
}
}

private boolean isMissing(String value) {
     return(value == null) || (value.trim().equals("")));
}
}

The part that works is when I try to call the ID in a jsp page. I do that with this:

${userBean2.username}

But to call it in a Servlet page I've tried everything under the sun and nothing has worked correctly.

I even tried a getAttributeNames thinking that would give me the info I needed but all I received was this: (bokay is the ID that was used to login to this particular session)

bokay: bokay
userBean2: HWpackage.UserBean2@257ccb2f

Any ideas as to what I'm suppose to use in the JSP page to display the ID, which in this case happens to be "bokay"?

Thanks everyone!

Upvotes: 1

Views: 837

Answers (1)

BalusC
BalusC

Reputation: 1109875

To get the username in the servlet just do

UserBean2 userBean2 = (UserBean2) session.getAttribute("userBean2");
String username = userBean2.getUsername();
// ...

Unrelated to the problem, your isMissing() method is at the wrong place. But this is more a design problem than a functional problem. I also wonder how 2 in the class name UserBean2 is relevant. The first code line in your "login verification page" is also unnecessary.

Upvotes: 1

Related Questions