错误500:通过servlet将数据插入数据库

时间:2017-08-26 18:08:29

标签: java servlets

我是Java中servlet等概念的初学者,最近我一直在努力学习它们。我试图在客户(customerid,用户名,密码)表中插入一行,其中customerid是自动生成的,但不幸的是我总是遇到错误500.这是我的servlet,我的HTML文件和我的控制台上显示的错误消息

newUserLoginServelet.java

package loginPackage;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import resources.MyUtil;

/**
 * Servlet implementation class NewUserLoginServlet
 */
@WebServlet(description = "Here a new/first time user sets up his/her login credentials.", urlPatterns = { "/NewUserLoginServlet" })
public class NewUserLoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public NewUserLoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        String SQL = "insert into table customer (username, password) values (" + "'" + username + "','" + password + "');" ;

        Connection connection = MyUtil.getConnection(); /*Import resources.MyUtil */

        PrintWriter out = response.getWriter();
        response.setContentType("text/html");

        try {
             /*Throws SQLException*/
            Statement statement = connection.createStatement();
            statement.executeQuery(SQL);
            out.println("New user credentials injected into the database.");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

的index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome to the SG Supermarket.</title>
</head>
<body>

<h1>Welcome to the SG supermarket.</h1>

<a href="signIn.html">In case you are not a new user.</a></br>
<a href="signUp.html">In case you are a new user.</a>
<
/body>
</html>

signUp.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User sign up (First time user)</title>
</head>
<body>
    <form action="NewUserLoginServlet">
    Please enter the credentials you wish to be.                </br> 
    Username : <input type="text" value="username">         </br>
    Password : <input type="password" value="password">     </br>
    <input type="submit" value="Submit your credentials.">  </br> 
    </form>
</body>
</html>

MyUtil.java

package resources;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MyUtil {
    private static Connection connection = null;
    private static String url = "jdbc:mysql://localhost:3306/mysql";
    private static String password = "*****";
    private static String user = "root";

    public static Connection getConnection()  {
        if (connection == null) {
            try { 
                Class.forName("com.mysql.jdbc.Driver"); // ClassNotFoundException
                connection = DriverManager.getConnection(url, user, password);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

        return (connection);
    }
}

错误讯息:

Type Exception Report

Description The server encountered an unexpected condition that prevented it from fulfilling the request.

Exception

java.lang.NullPointerException
    loginPackage.NewUserLoginServlet.doGet(NewUserLoginServlet.java:51)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Note The full stack trace of the root cause is available in the server logs.

我将数据插入数据库是否有问题,或者我是否无法在HTML和servlet之间建立连接?任何帮助将不胜感激。

我的数据库网址的屏幕截图 enter image description here

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SGCart2</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>    
  </welcome-file-list>

   <servlet>
    <description>NewUserLoginServlet</description>
    <display-name>NewUserLoginServlet</display-name>
    <servlet-name>NewUserLoginServlet</servlet-name>
    <servlet-class>loginPackage.NewUserLoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>NewUserLoginServlet</servlet-name>
    <url-pattern>/NewUserLoginServlet</url-pattern>
  </servlet-mapping>

</web-app>

1 个答案:

答案 0 :(得分:1)

这个sql语句不正确:

String SQL = "insert into table customer (username, password) values (" + "'" + username + "','" + password + "');" ;

它应该是:

String SQL = "insert into customer (username, password) values ('" + username + "','" + password + "');" ;

你也应该考虑做一个预备语句,它更简单,你不必乱用一起使用double +单引号,如果你的insert语句要大得多,那就太麻烦了:

  String username = request.getParameter("username");
  String password = request.getParameter("password");

try(Connection conn= MyUtil.getConnection()){

              PreparedStatement pst = conn.prepareStatement("insert into customer (username,password) values (?,?);");  
               pst.setString(1, username);
               pst.setString(2, password);

                pst.executeUpdate();    

          }catch (SQLException e) {
                e.printStackTrace();
            }

每当您插入,更新,删除时,您必须使用 .executeUpdate(); 而不是 .executeQuery();

另外,我建议查看MVC架构。 (模型视图控制器)......在servlet中执行数据库命令并不是一个好习惯。出于安全和组织原因,您应该将此逻辑分开。

你得到的错误是来自NewUserLoginServlet第51行的nullpointerexeption。这意味着这一行是错误的:

Statement statement = connection.createStatement();

在DBConnection类(MyUtil)中删除括号中的括号:

 return (connection);

应该只是:

 return connection;

编辑:尝试将此作为您的DBConnection类:

 public class MyUtil {
        private static Connection conn = null;
        private static String url = "jdbc:mysql://localhost:3306/mysql";
        public static Connection getConnection()  {
                try { 
                    Class.forName("com.mysql.jdbc.Driver"); 
                    conn = DriverManager.getConnection(url, "root", "*****");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            return conn;
        }

编辑2:在你的web.xml中你应该有这样的东西:

  <servlet>
    <description>NewUserLoginServlet</description>
    <display-name>NewUserLoginServlet</display-name>
    <servlet-name>NewUserLoginServlet</servlet-name>
    <servlet-class>loginPackage.NewUserLoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>NewUserLoginServlet</servlet-name>
    <url-pattern>/NewUserLoginServlet</url-pattern>
  </servlet-mapping>