2016-11-11 10 views
0

Я разрабатываю небольшое приложение сервлета sql, которое принимает команду SQL из текстовой области на странице html, отправляет команду сервлету, который создает соединение sql и помещает в набор результатов в arraylist. У меня все это, и я могу печатать имена столбцов в браузере в классе сервлета Java. Одна вещь, которую мне нужно сделать, это распечатать результаты в таблице, используя страницу JSP. Страница JSP будет выглядеть так же, как страница html, которую мы впервые использовали. Я не могу понять, как я собираюсь передать arraylist из сервлета на страницу JSP для отображения пользователю.Как я могу получить данные из сервлета на страницу 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> 

и вот код сервлета:

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 с сервлетами, чтобы, если можно получить необходимую информацию?

Я должен выполнить соединение sql в сервлете и не могу сделать соединение на странице JSP.

ответ

0

В вашем методе сервлета установить атрибут в контексте страницы, как показано ниже

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

В вашей JSP, используйте эль доступ к переменному:

${some} 
0

В сервлета, хранить данные в атрибуте запроса:

request.setAttribute("rows", rows); 

В JSP, используйте the JSTL в цикле по рядам:

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

НЕ использовать Java скриптлетов в вашем JSP ,

0

У вас есть несколько проблем с текущим кодом:

(1) Один экземпляр сервлета будет использоваться для всех потоков запросов, поэтому вы НЕ должны создавать переменные экземпляра для класса сервлета, то есть

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

Хорошая точка! Я заметил, что каждый раз, когда я перезагружаю страницу, у меня будут те же имена столбцов, которые добавляются к вектору! –

Смежные вопросы