问题
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?
回答1:
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;
}
来源:https://stackoverflow.com/questions/17488719/nullpointerexception-while-setting-a-bean