设置 bean 时出现 Nullpointerexception

点击这样的超链接后,我有一个操作 URL

I have an action URL after clicking a hyper link like so

/SocialStupendous/GetProfile.action?slno=3&slno=3

在我的 ActionClassexecute 方法中,我有以下代码

In my execute method of ActionClass I have the following code

public String execute() {
  int urislno=Integer.parseInt(getServletRequest().getParameter("slno"));
  System.out.println(urislno);
  bean.setUslno(urislno);       
}

我在执行 bean.setuslno(urislno) 时收到 NullPointerException.即使 urislno 被正确打印为 3.

I am getting NullPointerException when I am performing bean.setuslno(urislno). Even though urislno is printed properly as 3.

ProfileBean 类:

ProfileBean class:

public class ProfileBean {

  private int uslno;

  public int getUslno() {
    return uslno;
  }

  public void setUslno(int uslno) {
    this.uslno = uslno;
  }
}

为什么会这样?

推荐答案

bean 未初始化.你应该在动作中以某种方式初始化它

The bean is not initialized. You should initialize it somehow in the action

private ProfileBean bean = new ProfileBean(); 
//and add getter ans setter

然而,更好的方法是让容器为你做这件事.您只需要在 struts.xml

the better approach, however is let the container to do it for you. You just need to create a bean configuration in the struts.xml

<bean class="com.yourpackagename.ProfileBean" scope="default"/>

那么你就会有

private ProfileBean bean;

@Inject
public void setProfileBean(ProfileBean bean) {
  this.bean = bean;
}

并且您不需要解析参数请求,这已经由 params 拦截器完成,它是您的操作应该运行的 defaultStack 的一部分.您应该在您的操作中创建属性来保存参数值.

and you don't need to parse request for parameters, this is already done by the params interceptor which is a part of defaultStack that your action should run. You should create properties in your action to hold parameter values.

private Integer slno;

public Integer getSlno() {
    return slno;
}

public void setSlno(Integer uslno) {
    this.slno = slno;
}

动作看起来像

public String execute() {

   if (slno != null) {
     System.out.println(slno)
     bean.setUslno(slno);
   }

   ......
   return SUCCESS;
}

相关文章