I’m writing a simple web app that uploads some files to a server, runs some code and then emails the resulting files to the user. However, as the code can take a few hours to run after the user has uploaded some files I would like to forward them to a notification page. They should then be able to close the browser while processing continues on the server and wait for the results email.
After the uploading the files I have this code:
request.setAttribute("notification", details);
RequestDispatcher view = request.getRequestDispatcher("views/notification.jsp");
view.forward(request, response);
Then the processing code follows. The problem is that the view isn’t forwarded until all the processing is finished. Leaving the user hanging on the form page. If the user closes the browser the processing still continues but I would like to forward the user to a notification first.
You need to process your uploaded file asynchronously. Servlets assume that requests is served and connections is closed only after you leave the servlet. If you run the processing code inside a servlet, user might never get the view back.
For asynchronous processing you have several options, starting from normal threads, thread pool, JMS… Grab the file, send it to some thread running in background so that processing is non-blocking and return the view immediately.