1

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?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Ravi dunce
  • 23
  • 1
  • 5
  • Why are you accessing the parameter directly from the request in the first place? With regards to the NPE, shouldn't it be obvious what's wrong after seeing what's null? – Dave Newton Jul 06 '13 at 13:05
  • i want to get hold of those users whomsoever has clicked the url saying getprofile.action .The only way to catch the user was via his/hers slno. Hence i wanted to test if i am able to access the parameters from url which changes corresponding to users – Ravi dunce Jul 18 '13 at 13:25
  • There is no need to access the request directly, use av action property. – Dave Newton Jul 18 '13 at 13:33
  • 1
    Can you kindly brief me up on the av action , i dont know this as am new to struts – Ravi dunce Jul 18 '13 at 18:22
  • 1
    "An action property", it was a typo. – Dave Newton Jul 18 '13 at 18:41

1 Answers1

5

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;
}
Roman C
  • 49,761
  • 33
  • 66
  • 176