bluemunch bluemunch - 6 months ago 14
Java Question

Loop not exiting in Java Servlet

I am running a Java servlet on my local Tomcat server. When I run the script, the browser proceeds to perpetually open new tabs until I end the process in the task manager. Shouldn't this loop only open the browser once? Even if you ignore the while loop and only focus on the browser request I get the same behavior. I'm starting to believe this is a server issue as opposed to improper loop logic. Does this have to do with the try/catch? What's going wrong here?

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Desktop d = Desktop.getDesktop();

Boolean doOnce = false;

while (doOnce == false) {
try {
d.browse(new URI("http://localhost"));
doOnce = true;
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Answer

If you want to execute the try/catch block only once in while you should put the doOnce in your finally block :

try 
{
    d.browse(...);
} catch (URISyntaxException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}finally{
doOnce = true;
}

but if you want to exit from while when an exception occurred you should put it in catch block :

try 
{
    d.browse(...);
} catch (URISyntaxException e) {
     doOnce = true;
    // TODO Auto-generated catch block
    e.printStackTrace();
}