从Java Servlet将MySQL查询结果打印到JSP

时间:2012-11-16 18:12:33

标签: mysql jsp servlets output

目前我正面临以下两个问题:

1)当我运行像SELECT * FROM table;这样的命令时,它只返回列名。当我运行像SELECT columnName FROM table;这样的命令时,它会完美地显示输出。可能导致此错误的原因是什么?

2)当我运行INSERTDELETE命令时,我收到反馈消息,说明数据库已更新,但在检查数据库时,没有进行任何更改。任何人都可以在我的源代码中看到该子句出了什么问题吗?

以下是我的.java和.jsp文件:

databaseServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.ArrayList;

@SuppressWarnings("serial")

public class databaseServlet extends HttpServlet {
    private Connection conn;
    private Statement statement;

    public void init(ServletConfig config) throws ServletException {
        try {
            Class.forName(config.getInitParameter("databaseDriver"));
            conn = DriverManager.getConnection(
                    config.getInitParameter("databaseName"),
                    config.getInitParameter("username"),
                    config.getInitParameter("password"));
            statement = conn.createStatement();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ArrayList<String[]> out = new ArrayList<String[]>();
        ArrayList<String> columns = new ArrayList<String>();

        String query = request.getParameter("query");

        if (query.toString().toLowerCase().contains("select")) {
            //SELECT Queries
            try {
                ResultSet resultSet = statement.executeQuery(query.toString());
                ResultSetMetaData metaData = resultSet.getMetaData();
                int numberOfColumns = metaData.getColumnCount();
                for(int i = 1; i<= numberOfColumns; i++){
                    columns.add(metaData.getColumnName(i));
                }

                while (resultSet.next()){
                    String[] row = new String[numberOfColumns];
                    for (int i = 0; i < numberOfColumns; i++){
                        row[i] = (String) resultSet.getObject(i+1);
                    }
                    out.add(row);
                 }
            }
            catch (Exception f) {
                f.printStackTrace();
            }
        }
        else if (query.toString().toLowerCase().contains("delete") || query.toString().toLowerCase().contains("insert")) {
            //DELETE and INSERT commands
            try {
                conn.prepareStatement(query.toString()).executeUpdate(query.toString());
                columns.add("\t\t Database has been updated!");
            }
            catch (Exception l){
                l.printStackTrace();
            }
        }
        else {
            //Not a valid response
            columns.add("\t\t Not a valid command or query!");
        }
        request.setAttribute("query", query);
        request.setAttribute("resultSize",  out.size());
        request.setAttribute("queryResults", out);
        request.setAttribute("queryColumns", columns);
        RequestDispatcher dispatcher = request.getRequestDispatcher("/dbServlet.jsp");
        dispatcher.forward(request,  response);
    }
}

dbServlet.jsp

<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- dbServlet.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<%@ page import="java.util.ArrayList" %>
<head>
    <title>MySQL Servlet</title>
    <style type="text/css">
        table{border: 1px solid #FFF;}
        td{border: 1px dashed #FFF; padding: 3px; background-color: #5A5F64;}
        body{background-color: #182229; text-align: center; color: #FFF;}
        h1{font-family:"Arial", sans-serif, Helvetica;}
    </style>
</head>
<body>
    <h1>MySQL Servlet User-Interface</h1>
    <div style="width:500px; margin-right:auto; margin-left: auto; background-color:#131B21; padding: 20px;">
        <h3>Enter an SQL Command!</h3>
        <form action = "/database/database" method = "post">
        <p>
            <textarea name = "query" cols="28" rows="5"></textarea>
        </p>
        <p>
            <input type = "submit" value = "Run MySQL Servlet" />
            <input type = "reset" value = "Clear Command" />
        </p>
        </form>
        <hr>
        <TABLE id="results" align="center">
            <%
                ArrayList<String> columns = (ArrayList<String>)request.getAttribute("queryColumns");
                ArrayList<String[]> results = (ArrayList<String[]>)request.getAttribute("queryResults"); 
                out.println("<TR align='left'>");
                if(columns != null && !columns.isEmpty()){
                    for(String columnName: columns ){
                       out.println("<TD>"+columnName+"</TD>");
                    }
                }
                out.println("</TR>");
                //print data
                if(results != null && !results.isEmpty()){
                    for(String[] rowData: results){
                       out.println("<TR align='left'>");
                       for(String data: rowData){
                          out.println("<TD>"+data+"</TD>");
                       }
                       out.println("</TR>");
                    }
                }
            %>
        </TABLE>
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

调用select *查询时,您检查了是否抛出任何异常。 如果返回的对象不是string类型,则此行row[i] = (String) resultSet.getObject(i+1);可能会导致classCastExceptions。 您的列 numworkers 似乎对我来说就像一个整数。