在mysql数据库的jsp页面中显示多行

时间:2017-06-20 20:15:28

标签: java mysql jsp servlets jdbc

我试图在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 个答案:

答案 0 :(得分:1)

按照以下步骤操作:

  1. 使用所有getter和setter方法创建所有属性的POJO。

    public class Release {     private String uniqueId;     private String 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中找到相关的大量示例。