【问题标题】:How can i get data from a servlet into a JSP page?如何将数据从 servlet 获取到 JSP 页面?
【发布时间】:2017-03-26 03:42:58
【问题描述】:

我正在开发一个小型 sql servlet 应用程序,该应用程序从 html 页面中的文本区域接收 SQL 命令,将命令发送到建立 sql 连接并将结果集放入 arraylist 的 servlet。我已经完成了所有这些,我可以在 java servlet 类中将列名打印到浏览器。我需要做的一件事是使用 JSP 页面将结果打印到表格中。 JSP 页面看起来就像我们第一次使用的 html 页面。我不知道如何将数组列表从 servlet 获取到 JSP 页面以显示给用户。

这是 HTML 页面:

<html>
    <head>
        <title>WebApp</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body style="background-color:blue;">
    <center>
        <font color="white">
        <h1> Welcome to the Project 4 Remote Database Management System</h1>
        <hr>
        You are connected to the Project4 database. <br>Please enter any valid SQL query or update statement.<br>
        If no query/update command is given the Execute button will display all supplier information in the database. <br>All execution results will appear below. 
        <br>
        <br>
        <form action="NewServlet" method="post">
            <textarea rows="10" cols="60"name="command"></textarea>
            <br>
             <button type="submit">Execute Query</button>
             <button type="submit">Clear Command</button>
       </form>
        <hr>
        <h1>Database Results</h1>
        </font>
    </body>
</html>

这里是servlet代码:

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

/**
 *
 * @author KJ4CC
 */
public class NewServlet 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
     */
     Connection connection;
    Vector<String> columnNames = new Vector<String>();
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            String command = request.getParameter("command");
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            sqlConnection(command);
           //prints out column names into the browser. 
                out.println(columnNames);

        }
    }
    public void sqlConnection(String command){
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/project3";
        String user = "root";
        String pass = "Brandy?1994";
        ResultSet rs;
         try {
             Class.forName(driver);
         } catch (ClassNotFoundException ex) {
             Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
         }
         try {
             connection = DriverManager.getConnection(url,user,pass);
         } catch (SQLException ex) {
             Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
         }
         Statement stmt;
         try {
             stmt = connection.createStatement();
             rs = stmt.executeQuery(command);
             int colNum = rs.getMetaData().getColumnCount();

                    for (int i = 0; i < colNum; i++) {

                        columnNames.add(rs.getMetaData().getColumnLabel(i+1));


                    }
         } catch (SQLException ex) {
             Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
         }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

这里是 JSP 页面的开始:

    <html>
        <head>
            <title>WebApp</title>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
        </head>
        <body style="background-color:blue;">
        <center>
            <font color="white">
            <h1> Welcome to the Project 4 Remote Database Management System</h1>
            <hr>
            You are connected to the Project4 database. <br>Please enter any valid SQL query or update statement.<br>
            If no query/update command is given the Execute button will display all supplier information in the database. <br>All execution results will appear below. 
            <br>
            <br>
            <form action="NewServlet" method="post">
                <textarea rows="10" cols="60"name="command"></textarea>
                <br>
                 <button type="submit">Execute Query</button>
                 <button type="submit">Clear Command</button>
           </form>
            <hr>
            <h1>Database Results</h1>

           <%
    DO TABLE STUFF HERE TO OUTPUT SQL RESULTS
%>

            </font>
        </body>
    </html>

我想我将创建一个 javaBean 来存储数组,以便 JSP 页面可以访问列数组列表。然后使用 for 循环遍历数组列表,以便我可以创建表列。 如何将 JSP 页面链接到 servlet 以便获取所需信息?

我必须在 servlet 中进行 sql 连接,而无法在 JSP 页面中进行连接。

【问题讨论】:

    标签: java tomcat servlets


    【解决方案1】:

    您当前的代码几乎没有问题:

    (1) 单个 servlet 实例将在所有请求线程之间共享,因此您不应为 servlet 类创建实例变量,即

    Connection connection;
    Vector<String> columnNames = new Vector<String>();
    

    这两个变量应该在您的processRequest() 方法中创建,以便它们对每个请求线程都是本地的。

    (2) 你只是查询表的META DATA,所以你只能显示列名,但是如果你也想获取数据,你需要使用resultSetObj.hasNext()然后使用next()方法如下:

        while (rs.hasNext())
        {
           String X = rs.getString("empno");
           //Retrieve all data
           //add to a bean object
           //add to list
        }
       //Now return the list which contains the data
    

    您可以查看here 一个很好的例子。

    (3) 使用request.setAttribute 将结果设置为请求对象,然后您可以检索到下一个JSP(结果)页面。

    【讨论】:

    • 好点!我确实注意到每次我重新加载页面时,我都会在向量上附加相同的列名!
    【解决方案2】:

    在您的 servlet 方法中,在页面上下文中设置属性,如下所示

    HttpServletRequest req = (HttpServletRequest)request;
    .... // find out what to put
    req.getPageContext.setAttribute('some', objectYouFound);
    

    在你的jsp中,使用el来访问变量:

    ${some}
    

    【讨论】:

      【解决方案3】:

      在 servlet 中,将数据存储在请求属性中:

      request.setAttribute("rows", rows);
      

      在 JSP 中,使用the JSTL 循环遍历行:

      <c:forEach var="row" value="${rows}">
          ...
      </c:forEach>
      

      不要在您的 JSP 中使用 Java scriptlet。

      【讨论】:

        猜你喜欢
        • 2013-10-24
        • 1970-01-01
        • 1970-01-01
        • 2014-03-06
        • 1970-01-01
        • 2018-12-13
        • 1970-01-01
        • 1970-01-01
        • 2018-08-20
        相关资源
        最近更新 更多