To put a long-running query in the background, and keep refreshing your JSP until it's done, see below. There are better ways, though.
public class TestThread extends Thread
{
private Connection conn;
private boolean debugging = false;
private StringBuffer runtime;
public TestThread( Connection conn, StringBuffer runtime )
{
this.conn = conn;
this.runtime = runtime;
}
public void run() {
// Clean 'em (shouldn't be necessary)
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( "select sysdate()" );
rs.next();
Date d = rs.getDate(1);
long startTime = System.currentTimeMillis();
try {
Thread.sleep(1000*20); // Sleep 20 seconds
} catch (InterruptedException ie) {
// Do nothing
}
runtime.append(d);
} catch (SQLException se) {
runtime.append("-1");
}
}
}And here's the JSP page that keeps refreshing:
<%@ page language="java" session="true" import="blahblah"%>
<html>
<head>
<title>ThreadTest</title>
<%
Connection conn = null; // obtain your connection
// Set URL
String refreshURL = request.getRequestURL().toString();
// See if thread was fired
StringBuffer runtime = null;
Object obj = session.getAttribute("TestThreadRuntime0");
if( obj == null ) {
// Thread hasn't been fired before. Start it.
runtime = new StringBuffer("");
session.setAttribute("TestThreadRuntime0", runtime);
TestThread tt = new TestThread( conn, runtime );
tt.start();
} else {
// Thread has fired before. See whether it's finished.
runtime = (StringBuffer) obj;
}
// See if we're finished
boolean done = false;
if (runtime.length() > 0) {
done = true;
}
if (!done) {
%>
<meta http-equiv="Refresh" CONTENT="3; url=<%= refreshURL %>">
<%
}
%>
</head>
<body>
<%
if (!done) {
%>
Not done yet...
<p>
<%= obj %>
<%
}
else
{
// Reset stuff for next run
session.setAttribute("TestThreadRuntime0", null);
%>
We're done!! Runtime: <%= runtime %>
<%
}
%>
</body>
</html>