Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
114 views
in Technique[技术] by (71.8m points)

java - Nullpointerexception while setting a bean

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

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

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

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

ProfileBean class:

public class ProfileBean {

  private int uslno;

  public int getUslno() {
    return uslno;
  }

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

Why is this happening?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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"/>

then you would have

private ProfileBean bean;

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

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;
}

and the action will look like

public String execute() {

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

   ......
   return SUCCESS;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...