`
zhoujianghai
  • 浏览: 434500 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

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了下,还真有人遇到同样的问题。
<jsp:useBean id="product" class="com.example.Product" scope="session"></jsp:useBean>
   <!--此语句在Tomcat5.0以上版本中必须要有,否则出现上述错误-->

于是我在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())));


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics