日期:2014-05-17  浏览次数:20761 次

如何解决java.lang.NullPointerException问题
错误如下:
java.lang.NullPointerException
at org.lss.servlet.addBookToCart.doPost(addBookToCart.java:84)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:619)
这是addBookToCart.java代码:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

//设置响应代码
response.setContentType("text/html;chartset=gbk");
//创建session对象
//获取与请求对应的session,如果存在返回HttpSession对象,否则返回null
HttpSession session=request.getSession(false);
if(session==null){
RequestDispatcher dispatcher=request.getRequestDispatcher("shouye.jsp");
dispatcher.forward(request, response);
}
//取session中存储的书目
bookBean book=(bookBean)session.getAttribute("CURRENTBOOK");
//创建购物车,用HashMap来充当购物车

Map cart=(Map)session.getAttribute("cart");
if(cart==null){
cart=new HashMap();
//将购物车存放到session中
session.setAttribute("cart",cart);
}
cartItemBean cartItem=(cartItemBean)cart.get(book.getIsbn());
if(cartItem!=null){
cartItem.setNumber(cartItem.getNumber()+1);
}else{
cart.put(book.getIsbn(), new cartItemBean(book,1));

}
RequestDispatcher dispatcher=request.getRequestDispatcher("jsp/viewCart.jsp");
dispatcher.forward(request, response);
}


------解决方案--------------------
HttpSession session=request.getSession(false);
为啥要传一个false呢,去掉!
------解决方案--------------------
从代码来看,很大可能概率是:变量 book 为空。

所以调用 book.getIsbn() 时,抛出空指针异常

也就是说:
bookBean book=(bookBean)session.getAttribute("CURRENTBOOK");
在session中没有得到东西。
------解决方案--------------------
你第一次session.getAttribute("CURRENTBOOK");得到的book为null,而你cartItemBean cartItem=(cartItemBean)cart.get(book.getIsbn());又在使用他,肯定会有null异常的
------解决方案--------------------
bookBean book=(bookBean)session.getAttribute("CURRENTBOOK");//判断一下book是不是为空,可能就是它为空导致空指针
//创建购物车,用HashMap来充当购物车

Map cart=(Map)session.getAttribute("cart");
if