我正在尝试实现一个多线程 java servlet,我需要在其中发送每个传入请求的响应,下面是我的代码
public class RequestController extends HttpServlet {
private ExecutorService pool;
@Override
public void init() {
final int NTHREADS = 100;
pool = Executors.newFixedThreadPool(NTHREADS);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
BufferedReader br = request.getReader();
String msg = br.readLine(), temp;
while ((temp = br.readLine()) != null) {
msg += temp;
}
br.close();
if (msg == null) {
msg = request.getParameter("request");
if (msg == null) {
System.out.println("Invalid request");
return;
}
}
System.out.print("Request received: ");
System.out.println(msg);
pool.submit(new HandleRequest());
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Short description";
}
}
现在的问题是发送每个请求的响应。我试图通过传递 HttpServletResponse 响应对象来解决这个问题
pool.submit(new HandleRequest(response));
但这仅向最后一个请求发送响应。如何正确执行?请帮忙。