Я пишу часть кода для отображения списка организаций, которые поступают из базы данных MYSQL.Я использую аутентификацию формы JDBC Realm, поэтому я знаю, что моя база данных может быть запрошена и работает правильно.Моя страница JSP отображает все как обычно, когда я исключаю сервлет, но когда я включаю его, моя страница отображается пустой, только с цветом фона моего CSS и ничего больше.Я очень благодарен за любую помощь в выяснении, почему это происходит, и / или обходной путь, чтобы я мог отобразить этот список из базы данных.Весь соответствующий код, указанный ниже:
JSP-страница в вопросе:
<%@page import="SW.models.StudentOrg"%>
<%@page contentType="text/html" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:include page="GetOrgServlet" flush="true" />
<c:import url="/includes/header.html" />
<body>
<div id='container'>
<c:import url="/includes/navigation.html" />
<aside>
<img src='https://projecthelping.org/wp-content/uploads/2017/11/Your-Logo-here.png' width="200" height="200" alt='Organization Logo'>
<h3>[List of Upcoming Events Here]</h3>
<p>[Contact Information Here]</p>
</aside>
<section id='main'>
<h2>[Student Organization Name Here]</h2>
<p>
[Student Organization Description Here]
</p>
<p>
[Student Organizations Q&A Section Here]
</p>
<table>
<th>Org ID</th>
<th>Org Name</th>
<th>Org Description</th>
<c:forEach var="studentOrg" items="${studentOrgList.studentOrg}">
<tr>
<td>${studentOrg.OrgID}</td>
<td>${studentOrg.OrgName}</td>
<td>${studentOrg.OrgDescription}</td>
</tr>
</c:forEach>
</table>
</section>
<c:import url="/includes/footer.jsp" />
</div>
</body>
</html>
Сервлет в вопросе:
package SW.controllers;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import SW.data.DB;
import SW.models.StudentOrg;
import SW.models.StudentOrgList;
public class GetOrgServlet 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
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
StudentOrgList studentOrgList = DB.getStudentOrgs();
session.setAttribute("studentOrgList", studentOrgList);
}
// <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>
}
DB.java (где хранятся запросы, я 'используя getStudentOrgs в сервлете)
package SW.data;
import java.sql.*;
import SW.models.*;
public class DB {
public static StudentOrg selectStudentOrg(Integer OrgID) {
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT * FROM org "
+ "WHERE OrgID = ?";
try {
ps = connection.prepareStatement(query);
ps.setInt(1, OrgID);
rs = ps.executeQuery();
StudentOrg studentOrg = null;
if (rs.next()) {
studentOrg = new StudentOrg();
studentOrg.setOrgID(rs.getInt("orgID"));
studentOrg.setOrgName(rs.getString("orgName"));
studentOrg.setOrgDescription(rs.getString("orgDescription"));
}
return studentOrg;
} catch (SQLException e) {
System.out.println(e);
return null;
} finally {
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
public static StudentOrgList getStudentOrgs() {
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String query = "SELECT * FROM org";
try {
ps = connection.prepareStatement(query);
rs = ps.executeQuery();
StudentOrgList studentOrgList = new StudentOrgList();
while (rs.next()) {
StudentOrg studentOrg = new StudentOrg();
studentOrg.setOrgID(rs.getInt("OrgID"));
studentOrg.setOrgName(rs.getString("OrgName"));
studentOrg.setOrgDescription(rs.getString("OrgDescription"));
studentOrgList.addStudentOrg(studentOrg);
}
return studentOrgList;
} catch (SQLException e) {
System.err.println(e);
return null;
} finally {
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
}
Изображение запрашиваемой таблицы
Пул соединений
package SW.data;
import java.sql.*;
import javax.sql.DataSource;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class ConnectionPool {
private static ConnectionPool pool = null;
private static DataSource dataSource = null;
private ConnectionPool() {
try {
InitialContext ic = new InitialContext();
dataSource = (DataSource) ic.lookup("java:/comp/env/jdbc/milestone3");
} catch (NamingException e) {
System.out.println(e);
}
}
public static synchronized ConnectionPool getInstance() {
if (pool == null) {
pool = new ConnectionPool();
}
return pool;
}
public Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
System.out.println(e);
return null;
}
}
public void freeConnection(Connection c) {
try {
c.close();
} catch (SQLException e) {
System.out.println(e);
}
}
}
DatabaseUtil
package SW.data;
import java.sql.*;
public class DBUtil {
public static void closeStatement(Statement s) {
try {
if (s != null) {
s.close();
}
} catch (SQLException e) {
System.out.println(e);
}
}
public static void closePreparedStatement(Statement ps) {
try {
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
System.out.println(e);
}
}
public static void closeResultSet(ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
System.out.println(e);
}
}
}
Опять же, мне не обязательно отображать список таким образом, это всего лишь один из способов сделать это, я подумал, что знаю, как сделать, как я делал это ранее, но что-то не так, и яне могу найти это нигде.Поэтому я ценю любые предложения об этом решении или другом!