在jsp中是否有与ignore_user_abort()相同的php函数?

时间:2012-03-23 03:26:55

标签: php jsp

我想使用ajax来调用另一个JSP文件。 Ajax不会等待JSP的结果并重定向到下一页。如果我通过ajax调用PHP。当JS运行重定向时,PHP文件可以使用ignore_user_abort()来避免终止。 JSP中是否有类似的方法来做同样的事情?

1 个答案:

答案 0 :(得分:3)

在与请求线程不同的线程中执行任务。

你问如何在JSP中执行此操作非常奇怪。 JSP旨在以HTML格式呈现结果,而不是执行某些业务逻辑。你通常使用servlet。它还允许您更轻松地完成细粒度的Java内容。

嗯,鉴于这个servlet的基本启动示例,您必须能够使用ignore_user_abort(true)实现与PHP相同的功能:

@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.
    }

}

小心这一点。不要在所有servlet上实现此功能。只有那些绝对需要这种工作的人。不要将线程溢出。