设置bean时的Nullpointerexception [英] Nullpointerexception while setting a bean

查看:119
本文介绍了设置bean时的Nullpointerexception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击超级链接后我有一个操作网址

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

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

在我的执行方法中 ActionClass 我有以下代码

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

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

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

ProfileBean class:

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?

推荐答案

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中创建一个bean配置

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

这篇关于设置bean时的Nullpointerexception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆