Java. Getting IOException after trying to print on JSP page using simple scheduler(Timer, TimerTask). Need help

StackOverflow https://stackoverflow.com/questions/7357069

Question

i'm trying to make simple scheduler using Timer and TimerTask classses see the code below, inside of the task i just want to print "Hello, World!" on the page, but it throws IOException: Stream closed. Please help!

JSP page code:

<% Test t = new Test(out);%>

Test class code:

public class Test {
    public Test(JspWriter out){
        Timer timer = new Timer();
        LpdbTask lTask = new LpdbTask();
        lTask.out = out;
        timer.scheduleAtFixedRate(lTask, 1000*5, 1000*60);
    }
}

LpdbTask code:

public class LpdbTask extends TimerTask{
    public JspWriter out;
    public void run(){
        try {
            out.println("Hello, World!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Error:

java.io.IOException: Stream closed
    at org.apache.jasper.runtime.JspWriterImpl.ensureOpen(JspWriterImpl.java:204)
    at org.apache.jasper.runtime.JspWriterImpl.write(JspWriterImpl.java:312)
    at org.apache.jasper.runtime.JspWriterImpl.write(JspWriterImpl.java:342)
    at org.apache.jasper.runtime.JspWriterImpl.print(JspWriterImpl.java:468)
    at org.apache.jasper.runtime.JspWriterImpl.println(JspWriterImpl.java:576)
    at scheduler.LpdbTask.run(LpdbTask.java:14)
    at java.util.TimerThread.mainLoop(Unknown Source)
    at java.util.TimerThread.run(Unknown Source)
Was it helpful?

Solution

The Java code for a JSP all runs before the user sees your page at all. By the time the Timer fires, the JSP has already been sent to the browser and rendered; the stream is indeed closed because it's no longer needed. This just isn't something that's possible to do.

If you want time-dependent things to happen on your page in the user's browser, then you have to do it in Javascript, Flash, or a Java Applet; all of these run on the desktop, as opposed to your JSP, which runs on the server.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top