处理 servlet 时出错

发布于 2024-12-08 06:07:55 字数 4674 浏览 0 评论 0原文

我有以下 JSP 文件和 Servlet 文件

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>ABC Corporation</title>
    <h1>Terminal Login</h1>
</head>
<body>
    <form name="login" action="/WebAccount/LoginServlet?" method="post" />
    Username: <input type="text" name="username" value=""/>
    Password: <input type="text" name="password" value=""/>
    <input type="submit" value="LOGIN"/>

    Not User? Register Here: <input type="submit" action="/WebAccount/register.jsp" value="REGISTER">

</body>
</html>

Servlet 代码:

class LoginServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String username = request.getParameter("Username").toString();
        String password = request.getParameter("Password").toString();
        try {

            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/account";
            Connection conn = DriverManager.getConnection(url, "root", "school");

            Statement statement = (Statement) conn.createStatement();

            ResultSet rs = statement.executeQuery("SELECT * from Users where username='" + username + "' and password='" + password + "';");
            String user;
            String pass;

            while (rs.next()) {
                user = rs.getString(username).toString();
                pass = rs.getString(password).toString();

                if (username.equals(user) && password.equals(pass)) {
                    response.sendRedirect("http://www.google.com");
                    conn.close();
                }
            }
            if (!rs.next()) {
                out.println("Login failed");
                conn.close();
            }
        } catch (SQLException ex) {
             throw new ServletException("Cannot Connect", ex);
        } catch (ClassNotFoundException ex) {
            throw new ServletException("Login failed", ex);

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

我在处理 servlet 时收到此错误:

java.lang.NullPointerException

LoginServlet.processRequest(LoginServlet.java:38)
LoginServlet.doPost(LoginServlet.java:104)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

有任何错误吗?

I have the following JSP File and Servlet file

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>ABC Corporation</title>
    <h1>Terminal Login</h1>
</head>
<body>
    <form name="login" action="/WebAccount/LoginServlet?" method="post" />
    Username: <input type="text" name="username" value=""/>
    Password: <input type="text" name="password" value=""/>
    <input type="submit" value="LOGIN"/>

    Not User? Register Here: <input type="submit" action="/WebAccount/register.jsp" value="REGISTER">

</body>
</html>

Servlet Code:

class LoginServlet extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String username = request.getParameter("Username").toString();
        String password = request.getParameter("Password").toString();
        try {

            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/account";
            Connection conn = DriverManager.getConnection(url, "root", "school");

            Statement statement = (Statement) conn.createStatement();

            ResultSet rs = statement.executeQuery("SELECT * from Users where username='" + username + "' and password='" + password + "';");
            String user;
            String pass;

            while (rs.next()) {
                user = rs.getString(username).toString();
                pass = rs.getString(password).toString();

                if (username.equals(user) && password.equals(pass)) {
                    response.sendRedirect("http://www.google.com");
                    conn.close();
                }
            }
            if (!rs.next()) {
                out.println("Login failed");
                conn.close();
            }
        } catch (SQLException ex) {
             throw new ServletException("Cannot Connect", ex);
        } catch (ClassNotFoundException ex) {
            throw new ServletException("Login failed", ex);

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(LoginServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

I am getting this error while processing the servlet:

java.lang.NullPointerException

LoginServlet.processRequest(LoginServlet.java:38)
LoginServlet.doPost(LoginServlet.java:104)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

Any mistakes?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

阿楠 2024-12-15 06:07:55

错误消息准确地告诉您异常是在哪一行抛出的。阅读错误消息。它包含有用的信息。

我可以通过检查代码告诉您,此行将导致异常,因为输入字段名为 username (小写 u),并且您读取(因此为 null)参数 Username(大写 U):

String username = request.getParameter("Username").toString();

顺便说一句,为什么要在 String 上调用 toString()

The error message tells you exactly at which line the exception is thrown. Read the error message. It contains useful information.

I can tell you just by examining the code that this line will cause an exception since the input field is named username (lowercase u), and you read the (thus null) parameter Username (uppercase U):

String username = request.getParameter("Username").toString();

BTW, why are you calling toString() on a String?

尤怨 2024-12-15 06:07:55

那么“LoginServlet.java,第 38 行”到底是什么?看起来“out”可能为空?

如果问题确实出在响应“writer”对象上,则以下是一种可能的解释:

http://www.coderanch.com/ t/484052/Tomcat/Tomcat-关闭时返回 NullPointer

谢谢问题是response.getWriter()对象被声明为
在 servlet 中是全局的,因此它对所有线程都是通用的。如果有一个
线程关闭它,它曾经在其他线程中给出 NullPtrException。

So what exactly is at "LoginServlet.java, line 38"? It looks like "out" might be null?

If the problem is indeed with the response "writer" object, here's one possible explanation:

http://www.coderanch.com/t/484052/Tomcat/Tomcat-Returning-NullPointer-upon-closing

Thanks The problem was response.getWriter() object was declared as
global in servlet, so it became common to all threads. and if one
thread closes it, it used to give NullPtrException in other threads.

肥爪爪 2024-12-15 06:07:55

java.lang.NullPointerException
在 LoginServlet.processRequest(LoginServlet.java:38)

只需阅读跟踪的第一行。 LoginServlet 类的第 38 行(在 processRequest() 方法内)的某些内容为 null,而您的代码并不期望它是这样。

好吧,我要试试我的魔法球。您按如下方式声明了 2 个输入字段:

Username: <input type="text" name="username" value=""/>
Password: <input type="text" name="password" value=""/>

因此,分别使用参数名称 usernamepassword

但是,您尝试按如下方式访问它:

String username = request.getParameter("Username").toString();
String password = request.getParameter("Password").toString();

请注意大写的第一个字符!这不匹配。 getParameter() 将在此处返回 null,并且对 null 的(不必要的)toString() 调用将导致一个 NullPointerEXception。

相应地修复它:

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

有关使用 servlet 的更多提示,您可能会发现我们的 servlets wiki 页面也很有用。

java.lang.NullPointerException
at LoginServlet.processRequest(LoginServlet.java:38)

Just read the 1st line of the trace. Something at line 38 of LoginServlet class, inside the processRequest() method, is null while your code didn't expect it to be.

Well, I'll try my magic ball. You declared the 2 input fields as follows:

Username: <input type="text" name="username" value=""/>
Password: <input type="text" name="password" value=""/>

So, with the parameter names username and password respectively.

However, you're attempting to access it as follows:

String username = request.getParameter("Username").toString();
String password = request.getParameter("Password").toString();

Note the uppercased 1st character! This does not match. The getParameter() would return null here and the (unnecessary btw) toString() call on null will cause a NullPointerEXception.

Fix it accordingly:

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

For some more hints about using servlets, you may find our servlets wiki page useful as well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文