This question already has answers here:
What is a NullPointerException, and how do I fix it?
                                
                                    (12个答案)
                                
                        
                                2年前关闭。
            
                    
我正在用JSP开发电影租赁应用程序。在使用复选框选择电影后,当我进行迭代时,它给了我空指针异常。
这是Statement.jsp文件的代码,该文件正在为租借的电影创建语句...

<%@page language="java" %>
<%@page import="java.sql.*, java.util.*, mrs.*" %>
<html>
<head>
    <title>Movie Rental Application</title>
</head>
<body>
    <%@include file="Connection.jsp" %>

    <% if (session.getAttribute("Name") != null) {
            String[] checkboxes = null;
            String[] days = null;

            checkboxes = request.getParameterValues("c1");
            days = request.getParameterValues("t1");
            int i = 0;
            for (String title : checkboxes) {
                String Name = session.getAttribute("Name").toString();
                int code = 0;
                ResultSet rs = stmt.executeQuery("select Type from Movies where Title = '" + title + "'");
                String Type = rs.toString();
                if (Type.equalsIgnoreCase("REGULAR")) {
                    code = 0;
                }
                if (Type.equalsIgnoreCase("NEW RELEASE")) {
                    code = 1;
                }
                if (Type.equalsIgnoreCase("CHILDREN")) {
                    code = 2;
                }
                mrs.Movie m = new mrs.Movie(title, code);
                int day = Integer.parseInt(days[i]);
                i++;
                mrs.Rental r = new mrs.Rental(m, day);
                mrs.Customer c = new mrs.Customer(Name);
                c.addRental(r);
                stmt.executeQuery("insert into rents values('" + day + "','" + Name + "','" + title + "')");
                String result = c.statement();
                out.println(result);
            }
            stmt.close();
            con.close();
    %>
    <% }%>
</body>
</html>


这是例外...

最佳答案

您不检查复选框是否被选中。

 checkboxes = request.getParameterValues("c1");
 days = request.getParameterValues("t1");
 int i = 0;
 if(checkboxes!=null){
     for (String title : checkboxes) {
       if(title.equals("on")){
     // your code
     }
 }


您可以参考以下link来根据提到的条件检查复选框返回的值。

10-08 02:21