使用struts2在数据库上运行查询

时间:2014-07-30 09:32:55

标签: jsp struts2

我是struts2编程的新手。我想创建一个可以访问mysql数据库并在jsp页面上显示其结果的项目。我能够访问数据库并从中获取所需的值。

我在JSP页面上显示它们时遇到麻烦。 项目应该针对任何随机查询运行,因此我不知道结果集中的列数。如何在生成的JSP页面中显示它?

form.jsp

<%@ page import="java.util.*,java.io.*;" language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-tags" prefix="s2"%>
<!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>Get User Data</title>
</head>
<body bgcolor="#AABBCC">
<s2:form action="DBConnect">
<table>
<tr>
    <td><s2:textfield type="text" label="JDBC Driver" name="jdbcDriver" size="30" value="com.mysql.jdbc.Driver"></s2:textfield> </td>
</tr>
<tr>
    <td><s2:textfield type="text" label="JDBC URL" name="serverUrl" size="30" value="jdbc:mysql://localhost:3306/WorldDB" ></s2:textfield></td>
</tr>
<tr>
    <td><s2:textfield type="text" label="User Name" name="username" size="30" value="root" ></s2:textfield></td>
</tr>
<tr>
    <td><s2:textfield type="password" label="Password" name="password" size="30" value="i@Ap$_x7" ></s2:textfield></td>
</tr>
<tr>
    <td><s2:textfield type="text" label="Query" name="query" size="30" value="SELECT * FROM City;" ></s2:textfield></td>
</tr>
<tr>
    <td><s2:submit type="submit" name="submit_query" value="Submit" ></s2:submit></td>
</tr>
</table>
</s2:form>
</body>
</html>

struts.xml中

<?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE struts PUBLIC 
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="default" extends="struts-default">
        <action name="DBConnect" class="com.appperfect.training.DBConnect">
            <result name="success">/showDB.jsp</result>
        </action>
    </package>
</struts>

DBConnect.java

import java.sql.*;
import java.util.*;
import com.opensymphony.xwork2.ActionSupport;

public class DBConnect extends ActionSupport {
    private static final long serialVersionUID = 1L;

    private static String SUCCESS = "success";
    private static String FAILED = "failed";

    List<String> tableHeader = new ArrayList<String>();
    List<String> tableData = new ArrayList<String>();
    int columnCount = 0;

    private String jdbcDriver, serverURL, username, password, query;

    // Setter Methods
    public void setJdbcDriver(String driver) {
        this.jdbcDriver = driver;
    }

    public void setServerUrl(String url) {
        this.serverURL = url;
    }

    public void setUsername(String uname) {
        this.username = uname;
    }

    public void setPassword(String pass) {
        this.password = pass;
    }

    public void setQuery(String que) {
        this.query = que;
    }

    // Getter Methods
    public String getJdbcDriver() {
        return jdbcDriver;
    }

    public String getServerUrl() {
        return serverURL;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getQuery() {
        return query;
    }

    public List<String> getTableData() {
        return tableData;
    }

    public void setTableData(List<String> tData) {
        this.tableData = tData;
    }

    public List<String> getTableHeader() {
        return tableHeader;
    }

    public void setTableHeader(List<String> tHead) {
        this.tableHeader = tHead;
    }

    public int getColumnCount() {
        return columnCount;
    }

    @Override
    public String execute() throws Exception {

        String jdbcDriver, serverUrl, username, password, query;

        Connection con = null;
        Statement statement = null;
        ResultSet resultSet = null;
        ResultSetMetaData rsmd = null;

        jdbcDriver = getJdbcDriver();
        serverUrl = getServerUrl();
        username = getUsername();
        password = getPassword();
        query = getQuery();

        System.out.println(jdbcDriver + "   " + serverUrl + "   " + username
                + "   " + password + "   " + query);

        try {

            Class.forName(jdbcDriver);
            System.out.println("Attempting to establish connection to DB...");
            con = DriverManager.getConnection(serverUrl, username, password);
            System.out.println("Successfully connected to DB...");

            statement = con.createStatement();
            resultSet = statement.executeQuery(query);
            rsmd = resultSet.getMetaData();
            columnCount = rsmd.getColumnCount();

            String temp = null;
            int i = 1;

            for (i = 1; i <= rsmd.getColumnCount(); i++)
                tableHeader.add(rsmd.getColumnName(i));

            while (resultSet.next()) {
                temp = "";
                for (i = 1; i <= columnCount; i++) {
                    temp += resultSet.getString(i) + ",";
                }
                tableData.add(temp);
            }

            for (i = 0; i < tableHeader.size(); i++) {
                System.out.println(tableHeader.get(i));
            }

            for (i = 0; i < tableData.size(); i++) {
                System.out.println(tableData.get(i));
            }

        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        return SUCCESS;
    }

}

showDB.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-tags" prefix="s2" %>
<!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>Results</title>
</head>
<body>
<h2 align="justify">Query Results</h2>
<table>

<tr>
<s2:iterator value="tableHeader">
    <td> <s2:property/> </td>
</s2:iterator>
</tr>

<s2:iterator value="tableData">
    <tr> 
    <s2:iterator value="columnCount">
        <td> <s2:property value=""/> </td>
    </s2:iterator>
    </tr>
</s2:iterator>

</table>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

tableData是字符串的集合,以下应该可以工作。

<s2:iterator value="tableData">
    <tr>
        <td><s2:property/></td>
    </tr>
</s2:iterator>

如果您想单独显示各个列,则应更改tableData类似的内容,如下所示

List<String[]> tableData = new ArrayList<String[]>();
...
temp = new String[columnCount];
for (i = 0; i < columnCount; i++) {
   temp[i]= resultSet.getString(i+1);
}
tableData.add(temp);

并显示它

<s2:iterator value="tableData">
    <tr>
        <s2:iterator>
            <td><s2:property/></td>
        </s2:iterator>
    </tr>
</s2:iterator>