【问题标题】:jdbc program written in servlet using oracle in eclipse在eclipse中使用oracle用servlet编写的jdbc程序
【发布时间】:2017-02-13 03:13:15
【问题描述】:

我已经搜索了答案,但我得到了相关的答案。即使我的例外并不新鲜,但我无法找到答案。我遇到了一个异常,服务器遇到了一个内部错误,导致它无法完成这个

 request.Exception:java.lang.NullPointerException
    com.src.pkg.DepositServlet.doPost(DepositServlet.java:82)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

注意 Apache Tomcat/7.0.37 日志中提供了根本原因的完整堆栈跟踪。

我也会发送我的代码。它指向 DepositServlet 的 doPost() 方法,它也向下面的行显示错误- 语句 st = ((java.sql.Connection) con).createStatement(); 请帮我解决这个问题。

//DepositServlet.java
package com.src.pkg;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.corba.se.pept.transport.Connection;

/**
 * Servlet implementation class DepositServlet
 */
public class DepositServlet extends HttpServlet {
    Connection con;

    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */


    /**
     * @see Servlet#init(ServletConfig)
     */
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con=(Connection) DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","rekha");
        }
        catch(ClassNotFoundException e)
        {
            System.out.println(e);
        }
        catch(SQLException e)
        {
            System.out.println(e);
        }
    }

    /**
     * @see Servlet#destroy()
     */
    public void destroy() {
        // TODO Auto-generated method stub
        try
        {
            con.close();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */


    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    int ano = Integer.parseInt(request.getParameter("accno"));
    float amt = Float.parseFloat(request.getParameter("amount"));
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    try
    {
    Statement st = ((java.sql.Connection) con).createStatement();
        int n = st.executeUpdate("update account set balance = balance + "+amt+" where accno = "+ano);
        if(n==1)
        {
            out.println("<body bgcolor=green>");
            out.println("<h1> Successfully deposited </h1>");
        }
        if(n==0)
        {
            out.println("<body bgcolor=wheat>");
            out.println("<h1> Wrong a/c no </h1>");
        }
        st.close();
    }
        catch(SQLException e)
        {
            out.println("<body bgcolor=red>");
                out.println("<h1> Server problem </h1>");
            }
        out.println("</body>");
        out.println("</html>");
        out.close();
        }
    }


//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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

  <welcome-file-list>
    <welcome-file>deposit.html</welcome-file>

  </welcome-file-list>
  <servlet>

    <servlet-name>DepositServlet</servlet-name>
    <servlet-class>com.src.pkg.DepositServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>DepositServlet</servlet-name>
    <url-pattern>/DepositServlet</url-pattern>
  </servlet-mapping>
</web-app>


//deposit.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="cyan">
<center>
<h1> Deposit screen</h1>
<form action = "./DepositServlet" method = "post">
A/C No <input type="text" name="accno"> <br> <br>
Amount <input type="text" name="amount"> <br> <br>
<input type="submit" value="deposit">
</form>
</center>

</body>
</html>

【问题讨论】:

  • com.sun.corba.se.pept.transport.Connection 不是您正在寻找的连接 - 您想要 java.sql.Connection

标签: eclipse servlets jdbc


【解决方案1】:

您需要查看来自 Tomcat 的数据库 connection pooling docs。最终你需要三样东西。第一个是位于 Web 应用程序根目录的 META-INF/context.xml 文件。这看起来像:

<?xml version='1.0' encoding='utf-8'?>

<Context path="">
  <Resource name="jdbc/someName"
            auth="Container"
            type="javax.sql.DataSource"
            username="system"
            password="rekha"
            driverClassName="oracle.jdbc.driver.OracleDriver"
            url="jdbc:oracle:thin:@localhost:1521:xe"/>
</Context>

然后,在您的 Web 应用程序的 WEB-INF/lib 目录中,您需要放置 Oracle 瘦驱动程序 jar/zip 文件。最后,当您需要数据库连接时,您的代码将类似于:

import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

private static final String dbJNDIName = "jdbc/someName"; // matches context.xml name

public static Connection getConnection() {
    try {
        Context ctx = new InitialContext();

        DataSource ds = (DataSource)ctx.lookup( "java:comp/env/" + dbJNDIName );
        if( ds != null ) {
            return ds.getConnection();
         }
         else {
             // log error somehow
            }
        }
        catch( Exception e ) {
            // log error
        }
    return( null );
}

最后,当您需要在代码中建立数据库连接时,您可以通过调用此方法来实现。您的代码中有一个 java.sql.Connection 强制转换,通过正确的导入,将不需要它。确保仍然关闭您返回的连接 - 池会做正确的事情。

【讨论】:

    【解决方案2】:

    问题部分:

    首先,您需要知道这是一件危险且不稳定的事情。

    init”方法在servlet 被加载 时调用一次。 “doPost”方法可能会在数周、数月或数年内被调用很多数百或数千次。

    几乎所有数据库都会“超时”并断开打开连接,如果它们保持打开太久。 如果您只在“init”中打开一个连接,它甚至可能在您开始使用它之前“超时”。这也意味着您无法重新打开ga关闭的连接如果不重新加载 servlet,即重新启动您的网络服务器。 p>

    总而言之,打开数据库连接是“init”是一个坏事

    ====================

    现在,解决方案部分。

    您实际上应该在侦听器中执行此操作,更具体地说是 ServletContextListener。

    感谢 @stdunbar 的评论。

    1. (基本解决方案)您可以在 doPost() 中创建连接,而不是 init()。

    1. (高级解决方案)您可以使用 连接池,如 Tomcat JDBC 或 DBCP2。

    【讨论】:

    • 您的解决方案有何不同?通过在服务器的整个生命周期内保持连接打开,您使情况变得更糟。
    • 感谢您的建议。我会尝试你给定的解决方案。
    猜你喜欢
    • 2012-07-30
    • 1970-01-01
    • 2023-03-05
    • 2015-08-21
    • 1970-01-01
    • 2012-10-11
    • 2014-08-07
    • 1970-01-01
    • 2013-03-15
    相关资源
    最近更新 更多