D-Lef
D-Lef

Reputation: 1349

Servlet cannot access data from bean

I have a javabean called Userbean, where I store data for users.

public class UserBean
{
        public String uid;               //User ID
        public String password;          //Password    
        public String email;           //Email
        ...
        public UserBean() {}

        public void setUid(String str) {uid = str;}
        public String getUid() { return uid;}
        ...

I want to get tis data from a servlet, but in every servlet I must make a new Userbean and cannot use the "getData" methods. In a word, I cannot access data from a bean in a servlet. For exaple

String uid = userBean.getUid();

everytime returns

java.lang.NullPointerException

The only way I can avoid this error is to use

userBean = new UserBean();

but I want to use the data that is already put in the bean and not to create a new one. Any ideas? Thanks in advance.

Upvotes: 0

Views: 107

Answers (1)

developerwjk
developerwjk

Reputation: 8659

After you first instantiate the bean and set the values in one servlet, if you want to be able to access it in other servlets without recreating it, you need to save it in the session:

UserBean beanvar = new UserBean();
beanvar.setUID(uid);
session.setAttribute("somename", beanvar);

In another servlet,

UserBean beanvar = (UserBean)session.getAttribute("somename");
if(beanvar != null)
{ 
   String uid = beanvar.getUid();
  ... 
}

Upvotes: 2

Related Questions