设置bean时的Nullpointerexception

Rav*_*nce 1 java action struts2 nullpointerexception javabeans

点击超级链接后,我有一个操作URL

/SocialStupendous/GetProfile.action?slno=3&slno=3
Run Code Online (Sandbox Code Playgroud)

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

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

NullPointerException正在表演的时候bean.setuslno(urislno).即使urislno打印得当3.

ProfileBean 类:

public class ProfileBean {

  private int uslno;

  public int getUslno() {
    return uslno;
  }

  public void setUslno(int uslno) {
    this.uslno = uslno;
  }
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

Rom*_*n C 5

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

private ProfileBean bean = new ProfileBean(); 
//and add getter ans setter
Run Code Online (Sandbox Code Playgroud)

然而,更好的方法是让容器为你做.您只需要在中创建一个bean配置struts.xml

<bean class="com.yourpackagename.ProfileBean" scope="default"/>
Run Code Online (Sandbox Code Playgroud)

那么你会的

private ProfileBean bean;

@Inject
public void setProfileBean(ProfileBean bean) {
  this.bean = bean;
}
Run Code Online (Sandbox Code Playgroud)

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

private Integer slno;

public Integer getSlno() {
    return slno;
}

public void setSlno(Integer uslno) {
    this.slno = slno;
}
Run Code Online (Sandbox Code Playgroud)

而且动作看起来像

public String execute() {

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

   ......
   return SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)