2016-11-11 66 views
0

我正在開發一個小型的sql servlet應用程序,它接受來自html頁面文本區域的SQL命令,將該命令發送到一個使SQL連接成功的servlet,並將結果集放入一個數組列表中。我已經完成了所有這些工作,並且可以將列名打印到java servlet類中的瀏覽器中。我需要做的一件事就是使用JSP頁面將結果打印到表格中。 JSP頁面看起來就像我們第一次使用的html頁面。我無法弄清楚我將如何從servlet獲取arraylist到JSP頁面以顯示給用戶。如何將數據從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頁面可以訪問列arraylist。然後使用for循環遍歷數組列表,以便我可以創建表列。 如何將JSP頁面鏈接到servlet,以便能夠獲取所需的信息?

我必須在servlet中執行sql連接,並且不能在JSP頁面中建立連接。

回答

0

在你的servlet方法,在頁面的上下文設置屬性如下

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

在你的JSP,使用EL訪問變量:

${some} 
0

在servlet,存儲數據的請求屬性:

request.setAttribute("rows", rows); 

在JSP中,在行使用the JSTL循環:

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

不要在你的JSP使用Java小腳本。

0

你必須與你當前的代碼幾個問題: (1)一個servlet實例將在所有請求線程間共享,所以你不應該爲一個servlet類創建實例變量,即

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

這兩個變量應該在processRequest()方法內部創建,以便它們對每個請求線程都是本地的。 (2)您只查詢表格的元數據,因此您只能顯示列名稱,但如果您想要提取數據,則需要使用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(結果)頁面。

+0

好點!我確實注意到,每次我重新加載頁面時,我都會將相同的列名添加到向量中! –

相關問題