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
基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
