I am building a simple web app using Java, JSP, HTML, Apache Tomcat 10, MySQL, Connector J and Jakarta Servlet.
The user sees three buttons. Each button runs a query and redirects to a new page to display results.
Q: How can I display the results of each query on a new page?
Note: I can access the ResultSet object currently and that has allowed me to print the data to the console. But I am stuck trying to figure out how to use this ResultSet information on any page other than the one it is produced on.
I have included below my JSP file for reference. Thanks in advance.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.io.*, java.util.*,java.sql.*"%>
<%@ page import="jakarta.servlet.http.*, jakarta.servlet.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Query Page</title>
</head>
<body>
<form method="post">
<label for="button_A">Submit to display results of query 1 on new page</label> <input
type="submit" name="button_A" value="Submit1" />
<hr />
<label for="button_B">Submit to display results of query 2 on new page</label> <input
type="submit" name="button_B" value="Submit2" />
<hr />
<label for="button_C">Submit to display results of query 3 on new page</label> <input
type="submit" name="button_C" value="Submit3" />
</form>
<%
String button_A = request.getParameter("button_A");
if ("Submit1".equals(button_A)) {
queryDatabase();
String redirectURL = "QueryResult1.jsp";
response.sendRedirect(redirectURL);
}
String button_B = request.getParameter("button_B");
if ("Submit2".equals(button_B)) {
queryDatabase();
String redirectURL = "QueryResult2.jsp";
response.sendRedirect(redirectURL);
}
String button_C = request.getParameter("button_C");
if ("Submit3".equals(button_C)) {
queryDatabase();
String redirectURL = "QueryResult3.jsp";
response.sendRedirect(redirectURL);
}
%>
<%!public void queryDatabase() {
String connectionURL = "jdbc:mysql://127.0.0.1:3306/?user=coms363";
Connection connection = null;
Statement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionURL, "coms363", "password");
statement = connection.createStatement();
ResultSet resultSet = null;
String sqlQuery = "";
String outputString = "";
sqlQuery = "select id, ssn from employees where name = 'John'";
statement = connection.createStatement();
resultSet = statement.executeQuery(sqlQuery);
while (resultSet.next()) {
outputString += resultSet.getInt("id") + "....";
outputString += resultSet.getInt("ssn") + "\n";
}
System.out.println(outputString);
statement.executeBatch();
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Error:" + e.getMessage());
e.printStackTrace();
}
}%>
</body>
</html>