I have a requirement to display the database query results in a table format in JSP. I have tried various options using forEach and unable to achieve. Can you please help to get the JSP for the DB results from do Post method?
Here is my Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
Connection con = null;
Statement sta = null;
String url = "jdbc:mysql://localhost/cass_db";
String dbdriver = "com.mysql.jdbc.Driver";
String username = "app_user";
String password = "passwordxxxx";
try {
Class.forName(dbdriver);
con = DriverManager.getConnection(url, username, password);
sta = con.createStatement();
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String Sql = "Select * from doctors";
ArrayList<String> list = new ArrayList<String>();
String FileName = "/Users/asia/Downloads/test.log";
FileOutputStream file = new FileOutputStream(FileName);
try {
ResultSet rs = sta.executeQuery(Sql);
while (rs.next()) {
file.write(rs.getBytes(5));
file.write(System.getProperty("line.separator").getBytes());
list.add(rs.getString("doctor_nric"));
list.add(rs.getString("doctor_full_name"));
request.setAttribute("results", list);
}
con.close();
file.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.getRequestDispatcher("./DBResults.jsp").forward(request, response);
}
}
Database Table structure:
doctor_id, doctor_full_name, doctor_login_name, doctor_password, doctor_nric;
1, 'Daniel Ricciardo', 'dany', 'NZQbTKL2Z8pakBcUME3y/A==', 'G6345688X'
JSP code here
<form action="./DBResults" name="form_DBResults" method="post">
<label> Click here</label> <input type="submit" value="GetDBResults" id="submitBtn" />
</form>
<table border="1">
<c:forEach items="${results}" var="result">
<tr>
<td> <c:out value="${result.doctor_nric}" /></td>
<td> <c:out value="${result.doctor_full_name}" /> </td>
</tr>
</c:forEach>
</table>
The above jsp is not displaying the results in a table format, I am getting HTTP Status 500
Internal Server Error @
"<td> <c:out value="${result.doctor_nric}" /></td>"
If I use <td> <c:out value="${result}.{doctor_nric}" /></td>
then i get results like G6345688X.{doctor_nric}
but I am expecting database variable results in table format.
Can you please help to set the DB variable and its equivalent in JSP?