代码执行后的java.lang.NullPointerException

时间:2013-07-30 18:19:19

标签: jsp

我有这两个页面,在我将数据输入表单并提交后,它写道:

  

Založeníletadla
  显示java.lang.NullPointerException

我该怎么办这个问题....因为用户书面手册可以用Google搜索帮助我:(

admin.jsp:

<html>
<head>

</head>
<body>
<form method="post" action="vlozit.jsp">
<p>Založit Letadlo</p><br>
<table>
<tr><td>ID:</td>           <td><input type="text" name="id"></td></tr>
<tr><td>Model letadla:</td><td><input type="text" name="model"></td></tr>
<tr><td>Počet sedadel:</td><td><input type="text" name="sedadel"></td></tr>
</table>
<input type="submit" value="Založit letadlo">

</form>
</body>

和vlozit.php

<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<HTML>
<HEAD>
    <TITLE>Administrace</TITLE>
</HEAD>

<BODY>
    <H1>Založení letadla</H1>

    <%




String ID= request.getParameter("id");
String model = request.getParameter("model");
String sedadel = request.getParameter("sedadel");

try{



        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");


        Connection conn = DriverManager.getConnection("jdbc:odbc:ATBS", "CENTOS", "Shaman123");
if(conn != null){


        Statement statement = conn.createStatement();

        String command = "INSERT INTO letadlo (ID, model, sedadel) VALUES ('"+ID+"', '"+model+"', '"+sedadel+"')";
        PreparedStatement ps = conn.prepareStatement(command);
        if(ps != null){
        ps.execute();}}

conn.close();
}
catch(Exception e)
{
out.println(e); 
}



    %>
</BODY>

1 个答案:

答案 0 :(得分:0)

在调用方法之前,应该检查Connection对象是否为null。

 Connection conn = DriverManager.getConnection("jdbc:odbc:ATBS", "CENTOS", "Shaman123");

if(conn != null)
{
        Statement statement = conn.createStatement();

        String command = "INSERT INTO letadlo (ID, model, sedadel) VALUES ('"+ID+"', '"+model+"', '"+sedadel+"')";
        PreparedStatement ps = conn.prepareStatement(command);

        ps.execute();

        conn.close();     //Ideally it should be closed inside finally.
}

理想情况下ConnectionPrepareStatement应在finally块内关闭。