我正在尝试实现一个多线程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));
但是这只发送响应只是最后一个请求。 怎么做正确?请帮忙。
答案 0 :(得分:2)
不要打扰线程池,并向它发送请求。您正在使用的应用程序服务器已经为您执行此操作 - 每个请求通常在应用程序服务器管理的线程池中的单独线程中处理。
所以不要使用HandleRequest
,只需处理processRequest
方法中的请求,它将在其自己的线程中,并且不会阻止其他请求。
答案 1 :(得分:1)