从Java Servlet将数据插入PostgreSQL

时间:2012-04-21 22:27:36

标签: java postgresql servlets

我正在尝试使用java servlet将数据输入数据库。

package new;

import java.io.*;
import java.sql.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class display extends HttpServlet{
  public void init(ServletConfig config) throws ServletException{
  super.init(config);
  }


  protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        System.out.println("command: " + request.getParameter("command"));
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter();
            out.println("<title>Reg</title></head><body>");
        out.println("<h2>REG Form</h2><tr>");

        // HTMl Customer Input
        out.println("<form method=\"post\" action =\""
                + request.getContextPath() + "/display\" >");
        out.println("<table width=\"440\" border=\"0\">");
        out.println("<tr><th width=\"124\" scope=\"row\">Artist Info</th>");
        out.println("<td width=\"150\">Details</td>");
        // First input box: DOB
        out.println("<tr><th scope=\"row\">DOB:</th>");
        out.println("<td><input type=\"text\" name=\"dob\" size=\"20\" ></td>");
        out.println("</tr>");
        // Second input box: First Name
        out.println("<tr><th scope=\"row\">Firts name:</th>");
        out.println("<td><input type=\"text\" name=\"firtsname\" size=\"20\" ></td>");
        out.println("</tr>");
        // Third input box: Last name
        out.println("<tr><th scope=\"row\">Last name:</th>");
        out.println("<td><input type=\"text\" name=\"lastname\" size=\"20\" ></td>");
        out.println("</tr>");
        // Submit button
        out.println("</td></tr><tr><td valign=\"top\">");
        out.println("<input type=\"submit\" value=\"Register\"></td></tr>");
        out.println("</table></form>");
        out.println("</body></html>");
    }



  /**Process the HTTP Get request*/


  protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // Establish variables

        // HTML results
        response.setContentType("text/html");
        java.io.PrintWriter out = response.getWriter();
            out.println("<title>Result</title></head><body>");
        out.println("<h2>Welcome.</h2></br>");


        //Establish Variables for percentages of user input for each state and for each party
        int birthyear=0;
        String familyname = null, givenname = null;

        //DOB
        if (request.getParameter("birthyear").equals(""))   {
            out.println("Input date of birth");
        //otherwise, get the input
    }   else    {
        birthyear = Integer.parseInt(request.getParameter("birthyear"));
    }

        if (request.getParameter("familyname").equals(""))  {
            out.println("Input first name");

    }   else    {
        familyname = request.getParameter("familyname");
    }

        if (request.getParameter("givenname").equals(""))   {
            out.println("Input last name");

    }   else    {
        givenname = request.getParameter("givenname");
    }


  Connection connection=null;

  int id = 0;
  int agentid = id++;

  try {
  // Load the database driver
        Class.forName("org.postgresql.Driver");
        connection = DriverManager.getConnection(
                "jdbc:postgresql://localhost:5432/caglar", "postgres",
                "6666yyy");
   //Add the data into the database
  String sql = "insert into agent values (?,?,?,?)";
  PreparedStatement pst = 
  connection.prepareStatement(sql);
  pst.setInt(1, agentid);
  pst.setInt(2, birthyear);
  pst.setString(3, familyname);
  pst.setString(4, givenname);

   }
  catch(ClassNotFoundException e){
  out.println("Couldn't load database driver: " 
  + e.getMessage());
  }
  catch(SQLException e){
  out.println("SQLException caught: " 
  + e.getMessage());
  }
  catch (Exception e){
  out.println(e);
  }
  finally {
  // Always close the database connection.
  try {
  if (connection != null) connection.close();
  }
  catch (SQLException ignored){
  out.println(ignored);
  }
  }
  }
}

我在doPost中收到以下错误:

java.lang.NullPointerException
    S517.display.doPost(display.java:73)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

有人知道为什么吗?我只想使用servlet将数据添加到数据库中。驱动程序存在于库中。

第73行&amp; 74

    if (request.getParameter("birthyear").equals(""))   {
        out.println("Input date of birth");

1 个答案:

答案 0 :(得分:2)

您的错误在第73行:

birthyear = Integer.parseInt(request.getParameter("birthyear"));

我猜你的代码是doGet函数中的表单是发布你想要存储在数据库中的数据的表单。您的表单不包含birthyear字段。它的缺失使得request.getParameter(“birthyear”)返回null,在尝试从中解析int时会导致NullPointerException。

此外,您不仅要准备语句,还要执行它:

PreparedStatement pst = connection.prepareStatement(sql);
pst.setInt(1, agentid);
pst.setInt(2, birthyear);
pst.setString(3, familyname);
pst.setString(4, givenname);

// add this line
pst.executeUpdate();