简体   繁体   中英

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.

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();
  ... 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM