Attempted a bean operation on a null object(tomcat5.0以上版本)

今天做scwcd模拟题的时候,碰到这样一个题目:
A servlet sets a session-scoped attribute product with an instance of com.example.Product and
forwards to a JSP.
Which two output the name of the product in the response? (Choose two.)

A. ${product.name}
B. <jsp:getProperty name="product" property="name" />
C. <jsp:useBean id="com.example.Product" />
<%= product.getName() %>
D. <jsp:getProperty name="product" class="com.example.Product"
property="name" />
E. <jsp:useBean id="product" type="com.example.Product">
<%= product.getName() %>
</jsp:useBean>

答案:AB

我测试用的Product.java代码大致如下:
public class Product {

private String name;

public Product() {
this("123");
}
public Product(String name) {
this.name = name;
}
public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

我测试的时候写的servlet如下:
public class Test2 extends HttpServlet {

protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

req.getSession().setAttribute("product", new Product("123"));
req.getRequestDispatcher("/index.jsp").forward(req, resp);
}

}

index.jsp主要代码如下:
<jsp:getProperty name="product" property="name"/>

没想到出现了Attempted a bean operation on a null object异常。
查看index_jsp.java时,发现这样一段代码:
out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString(org.apache.jasper.runtime.JspRuntimeLibrary.handleGetProperty(_jspx_page_context.getAttribute("product", PageContext.PAGE_SCOPE), "name")));

记得使用<jsp:getProperty />时,查找指定bean的范围是依次是page,request,session,application的,怎么在这里只在page范围内查找呢。
这个标签很久没用了,很多东西都忘了。
于是google了下,还真有人遇到同样的问题。
[color=red] <jsp:useBean id="product" class="com.example.Product" scope="session"></jsp:useBean>
<!--此语句在Tomcat5.0以上版本中必须要有,否则出现上述错误--> [/color]
于是我在index.jsp加了<jsp:useBean id="product" class="com.example.Product" scope="session"></jsp:useBean>
在浏览器已测试,成功! 果然是这个原因。
此时再看了下index_jsp.java代码:
发现了如下代码:
out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString((((test.Product)_jspx_page_context.findAttribute("product")).getName())));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值