簡體   English   中英

在mysql數據庫的jsp頁面中顯示多行

[英]Display multiple rows in jsp page from mysql database

我正在嘗試在jsp頁面上顯示mysql表的多行。 我可以成功地從數據庫中讀取一行並將其顯示在我的jsp頁面上。 由於某種原因,我的代碼僅顯示一行。 您能幫我弄清楚如何在jsp頁面上顯示多行嗎?

tableView.jsp文件

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<style>
    table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
    }

    td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
    }

    tr:nth-child(even) {
    background-color: #dddddd;
    }
</style>
<style>
    body {margin:0;}

    .topnav {
      overflow: hidden;
      background-color: #333;
    }

    .topnav a {
     float: left;
     display: block;
     color: #f2f2f2;
     text-align: center;
     padding: 14px 16px;
     text-decoration: none;
     font-size: 17px;
    }

    .topnav a:hover {
     background-color: #ddd;
     color: black;
    }

    .topnav a.active {
     background-color: #4CAF50;
     color: white;
    }
    .topnave {
      overflow: hidden;
      background-color: #737373;
    }

    .topnave a {
     float: center;
     display: block;
     color: #f2f2f2;
     text-align: center;
     padding: 14px 16px;
     text-decoration: none;
     font-size: 17px;
     display: inline-block;
    }

    .topnave a:hover {
     background-color: #ddd;
     color: black;
    }

    .topnave a.active {
     background-color: #4CAF50;
     color: white;
    }
</style>
</head>
<jsp:include page="_header.jsp" />
<body>

<div class="topnav">
    <a href="${pageContext.request.contextPath}/">Home</a>
    <a class="active" href="${pageContext.request.contextPath}/tableView">Table View</a>
</div>
</body>
<head>
    <title>Table View</title>
</head>
<body>
<center>
<h3 style="font-family:verdana; font-size:30px; color:green">Table View</h3>

This is actual data from the Groguru database from the "sw_releases_table". <br><br>
<table>
  <tr>
    <th>Unique ID</th>
    <th>Release Name</th>
    <th>Update Date</th>
    <th>Release Date</th>
    <th>Release Notes</th>
    <th>File Name</th>
    <th>State</th>
  </tr>
  <tr>
    <td>${unique_id}</td>
    <td>${release_name}</td>
    <td>${update_date}</td>
    <td>${release_date}</td>
    <td>${release_notes}</td>
    <td>${filename}</td>
    <td>${state}</td>
  </tr>

</table>
<div class="topnave">
    <a href="${pageContext.request.contextPath}/views/addRowView.jsp">Add Row</a>
    <a href="${pageContext.request.contextPath}/deleteRow">Delete Row</a>
    <a href="${pageContext.request.contextPath}/editRow">Edit Row</a>
</div>>

</center>>
<jsp:include page="_footer.jsp" />


</body>

</html>

tableView.java文件

package com.grogurutest.simplewebapp.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Objects;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class tableView
 */
@WebServlet("/tableView")
public class tableView extends HttpServlet {
      public Connection connect = null;
      public Statement statement = null;
      public PreparedStatement preparedStatement = null;
      public ResultSet resultSet = null;;

      final public String host = "localhost:3306";
      final public String user = "user";
      final public String passwd = "Lasilka00";

      public String valuePicker(String columnName) throws Exception, ServletException, IOException {
             // This will load the MySQL driver, each DB has its own driver
                Class.forName("com.mysql.jdbc.Driver");


              // Setup the connection with the DB


              // Statements allow to issue SQL queries to the database
              connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/imported?autoReconnect=true&useSSL=false&user=" + user + "&password=" + passwd );
              statement = connect.createStatement();              
              // Result set get the result of the SQL query
              resultSet = statement.executeQuery("SELECT * FROM sw_releases_table");
              //writeResultSet(resultSet);

              String columnVal = "initial";
              while (resultSet.next()) {
          if (Objects.equals(columnName, "unique_id")){
                columnVal =  Integer.toString(resultSet.getInt("unique_id"));
                  System.out.println("columnVal = " + columnVal);
                  System.out.println("a checkpoint");
                  close();
                return columnVal;

            } if (Objects.equals(columnName, "release_name")){
                columnVal = resultSet.getString("release_name");
                  System.out.println("b checkpoint");
                  close();
                return columnVal;
          } if (Objects.equals(columnName, "update_date")){

                columnVal =  new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(resultSet.getDate("update_date"));
                  System.out.println("c checkpoint");
                  close();
                return columnVal;

          } if (Objects.equals(columnName, "release_date")){

                columnVal =  new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(resultSet.getDate("release_date"));
                  System.out.println("d checkpoint");
                  close();
                return columnVal;

          } if (Objects.equals(columnName, "release_notes")){

                columnVal =  resultSet.getString("release_notes");
                  System.out.println("e checkpoint");
                  close();
                return columnVal;

          } if (Objects.equals(columnName, "filename")){

                columnVal =  resultSet.getString("filename");
                  System.out.println("f checkpoint");
                  close();
                return columnVal;

          } if (Objects.equals(columnName, "state")){

                columnVal =  resultSet.getString("state");
                  System.out.println("g checkpoint");
                return columnVal;

          } else {
              System.out.println("h checkpoint");
              close();
              return "Not working";
          }   
        } 
              return columnVal;
}

      public void close() {
            try {
              if (resultSet != null) {
                resultSet.close();
              }

              if (statement != null) {
                statement.close();
              }

              if (connect != null) {
                connect.close();
              }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("exception with closing");
            }
          }



    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public tableView() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //response.getWriter().append("Served at: ").append(request.getContextPath());
                    try {
                        String unique_id = valuePicker("unique_id");
                        System.out.println(unique_id);
                        request.setAttribute("unique_id", unique_id);   

                        String release_name = valuePicker("release_name");
                        request.getSession().setAttribute("release_name", release_name);
                        System.out.println(release_name);

                        String update_date = valuePicker("update_date");
                        request.getSession().setAttribute("update_date", update_date);          
                        System.out.println(update_date);

                        String release_date = valuePicker("release_date");
                        request.getSession().setAttribute("release_date", release_date);
                        System.out.println(release_date);

                        String release_notes = valuePicker("release_notes");
                        request.getSession().setAttribute("release_notes", release_notes);
                        System.out.println(release_notes);

                        String filename = valuePicker("filename");
                        request.getSession().setAttribute("filename", filename);
                        System.out.println(filename);

                        String state = valuePicker("state");
                        request.getSession().setAttribute("state", state);
                        System.out.println(state);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        System.out.println("exception 7");
                    } finally {
                        close();
                    }
                    RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/views/tableView.jsp");
                    dispatcher.forward(request, response);


    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

請按照以下步驟操作:

  1. 使用所有getters和setters方法創建所有屬性的POJO。

    公共類Release {private String uniqueId; 私有字符串releaseName; //.... 根據規律

     //getters, setters public String getUniqueId() { return uniqueId; } public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } public String getReleaseName() { return releaseName; } public void setReleaseName(String releaseName) { this.releaseName = releaseName; } 

    }

  2. 在Java代碼中,創建POJO的列表。

    List<Release> releaseList = new ArrayList<Release>(); releaseList = getListofReleaseFromDB();

  3. 將整個列表設置為請求中的屬性。

    request.setAttribute("releaseList", releaseList);

  4. 在JSP中檢索此列表,並使用JSTL動態生成包含所有行的表。 您應該能夠在Stackoverflow中找到足夠的例子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM