-1

我是 servlet 的新手。我正在尝试使用带有 JDBC 和 OJDBC 的 java 连接到数据库。我已经为此编写了一个 java 代码。现在我需要在 Tomcat 服务器上运行它。所以我选择了 servlet。我使用 Netbeans IDE 完成了这项工作,在那里我选择了 servlet,并在 web.xml 中将类名作为 servlet 名称。我不知道我在哪里做错了。所以,我发布了有效的 java 代码:

public class convert {

    int i = 0, j = 0, k = 0;
    Connection conn = null;
    Connection connection = null;
    static int count = 0;

    // Following variables are required for assigning resultset values from
    // excel spreadsheet
    String name[] = null;
    String Title[] = null;

    Statement stmt1 = null;
    ResultSet NumOfRows = null;
    Statement stmt2 = null;
    ResultSet SpreadsheetValues = null;
    Statement stmt3 = null;
    ResultSet rs3 = null;

    int Rowcount = 0;

    // this static function required to connect database
    static {
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(spreadsheet2db.class.getName()).log(
                    Level.SEVERE, null, ex);
        }
    }

    // connect Sql database
    void ConnectSqlDB() throws SQLServerException, SQLException {
        // code
    }

    void ConnectExcelDB() throws SQLException {
        conn = DriverManager.getConnection("jdbc:odbc:condb", "", "");
    }

    // getRowcount() will return number of rows present in spreadsheet
    // Result of rowcount is used for array size
    void getRowcount() throws SQLException {
        // System.out.println("Number of rows in spreadsheet");
        // System.out.println(Rowcount);
    }

    void sheetValues() throws SQLException {
        stmt2 = conn.createStatement();
        // ExcelQueryString2 will give values of attributes
        while (SpreadsheetValues.next()) {
            // Assigning Spread sheet values to String array
            Cname[j] = SpreadsheetValues.getString("name");
            Title[j] = SpreadsheetValues.getString("Title");
            j++;
        }
    }

    public static void main(String args[]) throws SQLServerException,
            SQLException {
        convert a = new convert();
        a.ConnectSqlDB();
        a.ConnectExcelDB();
        a.getRowcount();
        a.sheetValues();
    }
}

我想知道如何将此代码转换为 Servlet?

4

2 回答 2

2

要处理 servlet 请求,您需要将类扩展为HttpServlet(from servlet-api.jar) 并相应地覆盖其方法doGet()and doPost()

POST使用方法或方法发送请求GET。使用哪种方法取决于您。

JDBC 连接在内部doGet()doPost()其他重写方法中完成init()

为此,您需要将一个外部 Jar(servlet-api.jar来自 apache)添加到您的项目中。

于 2011-12-27T06:41:40.297 回答
1

首先,您必须先了解 servlet 的基础知识。可能您可以参考一些简单的 Servlet 教程,也可能是一些示例项目。这是来自 Oracle 的 Java 教程链接:http: //docs.oracle.com/javaee/5/tutorial/doc/bnafd.html

在我看来,首先尝试做一个简单的服务。可能只是打印一个“Hello World”。一旦你清楚了 Sevlet 是如何工作的,你就可以尝试与其他部分的代码集成,比如 JDBC 细节。还要确保您的 JDBC 部分自己工作。

由于您是 Servelt 的新手,因此在调试大型 Serrvlet 类时会遇到困难,请使其简单化并尝试弄清基础知识。

于 2011-12-27T06:38:54.277 回答