Nullpointerexception while setting a bean(设置 bean 时出现 Nullpointerexception)
问题描述
点击这样的超链接后,我有一个操作 URL
I have an action URL after clicking a hyper link like so
/SocialStupendous/GetProfile.action?slno=3&slno=3
在我的 ActionClass
的 execute
方法中,我有以下代码
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);
}
我在执行 bean.setuslno(urislno)
时收到 NullPointerException
.即使 urislno
被正确打印为 3
.
I am getting NullPointerException
when I am performing bean.setuslno(urislno)
. Even though urislno
is printed properly as 3
.
ProfileBean
类:
ProfileBean
class:
public class ProfileBean {
private int uslno;
public int getUslno() {
return uslno;
}
public void setUslno(int uslno) {
this.uslno = uslno;
}
}
为什么会这样?
推荐答案
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
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:设置 bean 时出现 Nullpointerexception
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01