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
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
