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

标签 java tomcat servlets

我正在开发一个小型 sql servlet 应用程序,该应用程序从 html 页面的文本区域接收 SQL 命令,将命令发送到建立 sql 连接的 servlet,并将结果集放入数组列表中。我把所有这些都记下来了,我可以在 java servlet 类中将列名打印到浏览器。我需要做的一件事是使用 JSP 页面将结果打印到表格中。 JSP 页面看起来就像我们第一次使用的 html 页面。我不知道如何将 arraylist 从 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 页面中进行连接。

最佳答案

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

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

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

${some}

关于java - 如何从 servlet 获取数据到 JSP 页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40555955/

相关文章:

java - LWJGL 鼠标滚轮 getDWheel() 方法

java - 子线程异常

java - HibernateUtil 在 GlassFish 上工作,但不在 Tomcat 上工作

eclipse - 从已部署的 Eclipse Web 应用程序设置 Tomcat <Context> 参数

java - 如何从普通 Servlet 访问 Wicket WebSession

JavaMail - 附件文件名未正确显示 UTF-8 字符

Jar 文件中的 Java RMI 注册表

java - 部署在 Tomcat 上的 DBCP 中的死锁问题

java - 运行 servlet 时出错(apache tomcat 找不到 .properties 文件)

java - 获取通过 Java Servlet 中的 jquery ajax 发送的参数