首页 > 解决方案 > 将数据从 MySQL 加载到 JSP 页面中,无需表单

问题描述

我正在尝试使用 Eclipse 和 Tomcat 8 服务器将数据从 MySQL 数据库加载到 JSP 页面中。我的 .jsp 文件如下所示:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page import="java.util.ArrayList"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"     
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <jsp:forward page="/ProductDisplay" />
    <table border="2">
        <tr>
            <td>Id</td>
            <td>First Name</td>
            <td>Last Name</td>
            <td>Email</td>
            <td>Phone Number</td>
        </tr>
        <c:forEach var="patients" items="${patients}">
            <tr>
                <td>${patients.getPatientId()}</td>
                <td>${patients.getPatientfName()}</td>
                <td>${patients.getPatientlName()}</td>
                <td>${patients.getPatientEmail()}</td>
                <td>${patients.getPatientPhone()}</td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

.java servlet 文件:

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
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 ProductDisplay
*/
@WebServlet("/ProductDisplay")
public class ProductDisplay extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
    */
    public ProductDisplay() {
        super();
    }

    /**
    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws 
     ServletException, IOException {
        PatientsDao p = new PatientsDao();
        ArrayList<Patient> patients = p.getPatients();
        request.setAttribute("patients", patients);
        request.getRequestDispatcher("/Patient.jsp").forward(request,  response);
    }
}

数据库连接器类如下所示:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class PatientsDao {
    DBConnection mt = new DBConnection();
    Connection myConn = mt.myConn;

    private class DBConnection {
        public Connection myConn;

        public DBConnection() {

            try {
                Class.forName("com.mysql.jdbc.Driver"); 
                myConn = 
          DriverManager.getConnection("jdbc:mysql://localhost:3306/PatientsDB", "root", "");
            } catch (Exception exc) {
                exc.printStackTrace();
            }
        }
    }

    public ArrayList<Patient> getPatients() {
        ArrayList<Patient> patients = new ArrayList<>();
         try {
               PreparedStatement pst = 
                       myConn.prepareStatement("select * from Patients");
               ResultSet r = pst.executeQuery();
               while(r.next()) {
                   Patient p = new Patient();
                   p.setId(r.getInt("id"));
                   p.setfName(r.getString("fName"));
                   p.setlName(r.getString("lName"));
                   p.setEmail(r.getString("Email"));
                   p.setPhone(r.getString("Phone"));
                   patients.add(p);
                }
              }
               catch (SQLException exc) {
                    System.out.println("An error occured. Error: " + exc.getMessage());
           }
         return patients;
    }
}

如果我错了,请纠正我,但我相信在运行 Tomcat 服务器时会调用 .java servlet 类,并且无需任何操作即可将数据库中的信息加载到 JSP 页面中。但是,在我的情况下不会发生这种情况。一旦我启动 Tomcat 服务器并导航到 Patient.jsp 页面,唯一显示的是表头(不是来自数据库)。不显示来自 MySQL 数据库的数据。

我知道这不是 MySQL 问题,因为如果我添加表单并使用按钮,我可以成功加载所有数据。单击按钮并调用 doGet 方法后,所有内容都已成功加载。

我的问题是,如何在不单击按钮或链接的情况下自动加载数据?我正在做研究,显然所有信息都应该自动加载。然而,这在我的情况下不会发生。我错过了什么吗?先感谢您!

标签: javamysqleclipsejsp

解决方案


不,你错了。

Servlet 在您调用它时首次加载(例如转到Patient.jsp)。

但是当你去Patient.jsp工作时,只有 servlet Patient.jsp(jsp 页面自动转换为 servlet 类),而你的 servlet /ProductDisplay根本不工作。

当您调用 Patient.jsp 时,您的请求属性为空,因为 ProductDisplay 不起作用。

你有三种方式:

1) 你应该从 /ProductDisplay 页面开始

2) 或者添加 index.jsp 页面并从这个页面开始。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<jsp:forward page="/ProductDisplay" />
</body>
</html>

3) 和错误的变体 - 使用代码将 scriptlet 添加到 Patient.jsp 页面并从该页面开始

PatientsDao p = new PatientsDao();
ArrayList<Patient> patients = p.getPatients();
request.setAttribute("patients", patients);

记住永远不要直接调用 servlet。只能通过任何 servlet。这是不好的做法


推荐阅读