How does a single servlet handle multiple requests from client side

前端 未结 3 1908
梦如初夏
梦如初夏 2021-01-30 17:58

How does a single servlet handle multiple client requests coming in the form of user requests ? Based on the singleton design pattern I know we get a single instance of servlet

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-30 18:25

    Struts/Spring frameworks are actually written on top of Servlet specification so doesn't matter what you use underneath it use Servlets.

    You are right, Only single instance of Servlet is created, but that instance is shared across multiple threads. For this reason you should never have shared mutable states in your Servlets.

    For example you have following servlet mapped to http://localhost/myservlet

    class MySerlvet extends HttpServlet {
    
         public void doGet(HttpServletRequest req, HttpServletResponse res) {
              // Get Logic
         }    
    }
    

    The Web Server will have something similar (Not necessarily same) in its code.

    MyServlet m = new MyServlet(); // This will be created once
    
    // for each request for http://localhost/myservlet
    executorService.submit(new RequestProcessingThread(m));
    

提交回复
热议问题