0

好的,所以对于我们的 Uni 项目,我们正在创建一个网站来存储有关教堂的信息(我知道非常有趣 -.-)。

基本上,它只需要在数据库中有教堂信息,当用户点击或搜索教堂时,它需要从数据库中提取教堂信息和用户评论。

到目前为止,我有一个 HTML 表单,它向 servlet/数据库提供注释并使用结果集输出它。我只是想知道处理多个信息的最佳方法是什么,因为现在我正在尝试同时提供评论和教会信息,我对如何存储它有点迷茫。

提前致谢!

哦,这是我的参考代码:

HTML

    <form method="get" action="dbtest" id="form1">
        <fieldset>
        <p>Please enter you're Name:</p>
        <input type="text" name="author" size="10" id="name"/><br />
        <p>Please enter you're Email here:</p>
        <input type="text" name="author_email" size="10" id="email"/><br />
        <p>Please enter you're comment here:</p>
        <input type="text" name="comment_text" size="10" id="comment"/><br />
        <p>
        <input type="submit" value="Submit" name="submit_button" />
        </p>
        </fieldset>
    </form>

小服务程序

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author mxk12ycu
 */
public class dbtest 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 {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String authorName = request.getParameter("author");
        String authorEmail = request.getParameter("author_email");
        String commentText = request.getParameter("comment_text");


        try {
            //Holding SQL statement
            String SQL;
            String insertSQL;

            //insertSQL = "INSERT INTO comments VALUES('0002')" + authorName + authorEmail + commentText + ("('29 Nov 2012','002')");
            //insertSQL = "INSERT INTO comments VALUES (default,'Ryan H','Test@hotmail.com','TestComments','29 Nov 2012','1')";

           //insertSQL = "INSERT INTO comments (author, author_email, comment_text, comment_date, church_id) VALUES ('" + authorName + "'," + "'" + authorEmail + "'," + "'" + commentText + "', '29 Nov 2012', '1')";
           //insertSQL = "INSERT INTO comments VALUES ('Ryan Holder', 'test@hotmail.com', 'Comment here', '30 Nov 2012', 'default', '1')";
            insertSQL = "INSERT INTO comments VALUES (default, " + "'" + authorName + "'," + "'" + authorEmail + "'," + "'" + commentText + "', '29 Nov 2012', '1')";
            SQL = "SELECT * FROM churches, comments";

            Class.forName("org.postgresql.Driver");

            Connection connection = DriverManager.getConnection(
                    "jdbc:postgresql:ChurchSearch",
                    "postgres",
                    "*****");

            Statement statement = connection.createStatement();

            statement.executeUpdate(insertSQL);

            ResultSet resultSet = statement.executeQuery(SQL);


             /* TODO output your page here. You may use following sample code. */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Test Comment Servlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet test at " + request.getContextPath() + "</h1>");
            out.println("<h2>Comment Form</h2>");

            while (resultSet.next()) {
            out.println("<p>");
            out.println(resultSet.getString("author"));
            out.println("</p>");
            out.println("<p>");
            out.println(resultSet.getString("author_email"));
            out.println("</p>");
            out.println("<p>");
            out.println(resultSet.getString("comment_text"));
            out.println("</p>");
            }
            out.println("</body>");
            out.println("</html>");

            connection.close();
        } 
        catch (Exception e) {
            System.err.println("Error: " + e);
        }
        finally {            
            out.close();
        }
    }
4

2 回答 2

1

您可以使用MVC 模式。另一方面,您必须确保关闭与数据库的连接。

Connection conn = null;
try {
    conn = // get connection;

    // do database operations

} catch (final SQLException e) {
    throw new DAOException(e);
} finally {
    if (conn != null) {
        try {
            conn.close();
        } catch (final SQLException ex) {
            LOG.warning("message warning to log");
        }
    }
}

这将释放连接使用的所有资源。

关于 MVC,您可以在Integrating Servlets and JSP: The Model View Controller (MVC) Architecture中找到更多信息。您还可以使用像 Struts、Spring MVC 这样的框架。

于 2012-12-06T22:11:46.197 回答
0

创建一个DAO(数据库访问对象)类..处理连接。

 public class DAO {

static private Connection conn = null;
static private String URL = "jdbc:mysql://localhost/<databse name>";
static private String USERNAME = "root";
static private String PASSWORD = "root";
static private String DRIVER = "com.mysql.jdbc.Driver";


private static Connection getConnection() throws ClassNotFoundException,
        SQLException {

    if (conn == null) {
        Class.forName(DRIVER);
        System.out.println("Driver Initailizing");
        conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }
    return conn;
}

public static ResultSet selectQuery(String query) throws SQLException,
        ClassNotFoundException {

    //Read the query from the servlet class only SQL query
    System.out.println(query);
    ResultSet rs = DAO.getConnection().createStatement().executeQuery(query);
            //return the result set back to servlet class
    return rs;
}

谢谢,

帕万

于 2012-12-06T19:09:30.077 回答