在jsp中是否有相同的PHP函数ignore_user_abort()? [英] Is there any same php function of ignore_user_abort() in jsp?
问题描述
我想使用ajax来调用另一个JSP文件. Ajax不会等待JSP的结果并重定向到下一页.如果我通过ajax调用PHP.当JS运行重定向时,PHP文件可以使用ignore_user_abort()来避免终止. JSP中是否有任何类似的方法可以做相同的事情?
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???
推荐答案
在与请求线程不同的线程中执行任务.
Do the task in a different thread than the request thread.
您在问如何在JSP中执行此操作是很奇怪的. JSP 旨在以HTML形式显示结果,而不执行某些业务逻辑.您通常在此处使用 servlet .它还使您可以更轻松地执行细粒度的Java任务.
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.
}
}
对此要小心.不要在所有servlet上都实现这一点.只有那些绝对需要这种工作的人.请勿将线程浪费在此上.
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.
这篇关于在jsp中是否有相同的PHP函数ignore_user_abort()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!