我想在Java中使用doPost方法结束之前获取HTTP状态代码。例如在Python中有self.send_response(200)
,它以异步方式发送状态?
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*
*/
@SuppressWarnings("unchecked")
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Final result object
//I want to send a http status code 200 before the task running
myThreadPool = Executors.newFixedThreadPool(2);
Future taskOne = myThreadPool.submit(new Runnable() {
@Override
public void run() {
try {
try {
// My first task
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
// Task two
.
.
答案 0 :(得分:0)
我不完全确定您发布的代码的意图是什么,但我猜你想要某种异步处理,以便在请求完成之前将一些数据发送到客户端?
为此,请参阅异步servlet,例如:https://blogs.oracle.com/enterprisetechtips/entry/asynchronous_support_in_servlet_3
有一个很好的例子似乎正在服务于我想要实现的目标:
@WebServlet("/foo" asyncSupported=true)
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) {
...
AsyncContext aCtx = request.startAsync(req, res);
ScheduledThreadPoolExecutor executor = new ThreadPoolExecutor(10);
executor.execute(new AsyncWebService(aCtx));
}
}
public class AsyncWebService implements Runnable {
AsyncContext ctx;
public AsyncWebService(AsyncContext ctx) {
this.ctx = ctx;
}
public void run() {
// Invoke web service and save result in request attribute
// Dispatch the request to render the result to a JSP.
ctx.dispatch("/render.jsp");
}
}