繁体   English   中英

如何从servlet获取数据到JSP页面?

[英]How can i get data from a servlet into a JSP page?

我正在开发一个小的sql servlet应用程序,它从html页面的文本区域接收SQL命令,将命令发送到进行sql连接的servlet并将结果集放入arraylist。 我把所有这些都打倒了,我可以在java servlet类中将列名打印到浏览器中。 我需要做的一件事是使用JSP页面将结果打印到表中。 JSP页面看起来就像我们第一次使用的html页面。 我无法弄清楚我将如何从servlet获取arraylist到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页面可以访问列arraylist。 然后使用for循环迭代数组列表,以便我可以创建表列。 我怎么能将JSP页面链接到servlet,以便能获得所需的信息?

我必须在servlet中进行sql连接,并且无法在JSP页面中建立连接。

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

request.setAttribute("rows", rows);

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

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

不要在JSP中使用Java scriptlet。

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

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

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

${some}

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

(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

你可以在这里看一个很好的例子。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM