Is there any same php function of ignore_user_abort() in jsp?

只愿长相守 提交于 2021-02-08 11:18:22

问题


I would like to using ajax to call another JSP file. Ajax will not wait for the result from JSP and redirect to next page. If I am calling PHP by ajax. The PHP file can use ignore_user_abort() to avoid the termination when the JS running redirection. Is there any similar method in JSP to do the same thing???


回答1:


Do the task in a different thread than the request thread.

That you're asking how to do this in a JSP is quite strange. A JSP is intented to present the results in HTML, not to perform some business logic. There you normally use a servlet for. It also allows you to do more easily fine grained Java stuff.

Well, given this basic kickoff example of a servlet, you must be able to achieve the same as in PHP with ignore_user_abort(true):

@WebServlet("/someurl")
public class SomeServlet extends HttpServlet {

    private ExecutorService executor;

    @Override
    public void init() {
        executor = Executors.newFixedThreadPool(10); // Create pool of 10 threads.
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // First collect necessary request data.
        Map<String, String> params = request.getParameterMap();

        // Task is your custom class which implements Callable<SomeResult> and does the job accordingly in call() method.
        Task task = new Task(params);

        // Task is now in a queue and will run in a separate thread of the pool as soon as possible.
        Future<SomeResult> future = executor.submit(task); 

        // Current request will block until it's finished. If client aborts request, the task will still run in background until it's finished.
        SomeResult someResult = future.get(); 

        // Now do your thing with SomeResult the usual way. E.g. forwarding to JSP which presents it.
        request.setAttribute("someResult", someResult);
        request.getRequestDispatcher("/WEB-INF/someResult.jsp").forward(request, response);
    }

    @Override
    public void destroy() {
        executor.shutdownNow(); // Very important. Or your server may hang/leak on restart/hotdeploy.
    }

}

Be careful with this. Don't implement this on all servlets. Only those where this kind of job is absolutely necessary. Don't spill threads to this.



来源:https://stackoverflow.com/questions/9833795/is-there-any-same-php-function-of-ignore-user-abort-in-jsp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!