简体   繁体   English

Servlet无法从bean访问数据

[英]Servlet cannot access data from bean

I have a javabean called Userbean, where I store data for users. 我有一个名为Userbean的javabean,我为用户存储数据。

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. 我想从servlet获取tis数据,但在每个servlet中我必须创建一个新的Userbean并且不能使用“getData”方法。 In a word, I cannot access data from a bean in a servlet. 总之,我无法从servlet中的bean访问数据。 For exaple 为了exaple

String uid = userBean.getUid();

everytime returns 每次都回来

java.lang.NullPointerException 显示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. 但我想使用已经放在bean中的数据而不是创建一个新的数据。 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: 在第一次实例化bean并在一个servlet中设置值之后,如果您希望能够在其他servlet中访问它而不重新创建它,则需要将其保存在会话中:

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

In another servlet, 在另一个servlet中,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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