日期:2014-05-20  浏览次数:20748 次

空指针异常问题
这是jsp页面的代码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <title>My JSP 'jspShopCar.jsp' starting page</title>
  </head>
  <body>
  <h3>选择所需的商品</h3>
  <form name = "form1" action = "jspShopCar.jsp" method = "post">
  <select name = "item">
  <option>ASP.NET</option>
  <option>C++</option>
  <option>C语言</option>
  <option>THINGING IN JAVA </option>
  <option>ORCALE</option>
  <option>SQL/PLUS</option>
  </select>
  <input type = "submit" name = "submit" value = "Add">
  <input type = "submit" name = "submit" value = "Remove">
  </form>
  </body>
</html>
<jsp:useBean id = "beanCar" scope = "session" class = "chap7.ex.ShoppingCar"/>
<jsp:setProperty name = "beanCar" property = "*"/>
<%
String tmpbtn = request.getParameter("submit");
String tmpname = request.getParameter("item");
if(tmpbtn!=null){
out.print("<hr size = '1' noshade = 'noshade' />");
out.print("<h4>购物车中的商品:</h4>");
}
if(tmpbtn.equals("Add")){
beanCar.AddItem(tmpname);
}
if(tmpbtn.equals("Remove")){
beanCar.RemoveItem(tmpname);
}
out.print("<ol>");
String[] item = beanCar.getItems();
for(int i = 0;i<item.length;i++){
out.print("<li>" +item[i] +"</li>");
}
out.print("</ol>");
beanCar.reset();
%>
==============================================
这个是bean的代码
package chap7.ex;
import java.util.*;
public class ShoppingCar {
Vector v = new Vector();
String submit = null;
String item = null;
public void AddItem(String name){
v.addElement(name);
}
public void RemoveItem(String name){
v.removeElement(name);
}
public void setItem(String name){
item = name;
}
public void setSubmit(String s){
submit= s;
}
public String[] getItems(){
String[] s = new String[v.size()];
return s;
}
public void reset(){
item = null;
submit = null;
}
}
我一执行jsp就会出现空指针异常,调了好几天了,大家帮帮忙吧

------解决方案--------------------
if(tmpbtn.equals("Add")){
beanCar.AddItem(tmpname);
}
if(tmpbtn.equals("Remove")){
beanCar.RemoveItem(tmpname);
}


改if("Add".equals(tmpbtn)){
beanCar.AddItem(tmpname);
}
if("Remove".equals(tmpbtn)){
beanCar.RemoveItem(tmpname);
}

如果tmpbtn获取是null值,那是用equals方法的时候当然会出现npe