title: Adding a dynamic servlet using servlet 3.0 throws exception
body: <p>I need to create add servlets at runtime. When I run the following code.</p>
  
  <pre><code>protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException 
      {
  
          response.setContentType("text/html;charset=UTF-8");
          PrintWriter out = response.getWriter();
          try {
  
              out.println("&lt;html&gt;");
              out.println("&lt;head&gt;");
              out.println("&lt;title&gt; URI out&lt;/title&gt;");
              out.println("&lt;/head&gt;");
              out.println("&lt;body&gt;");
              Integer generatedKey = Math.abs(randomiser.nextInt());
              out.print(generatedKey);
  
              createServlet(Integer.toString(generatedKey),request.getServletContext());
  
          } finally {
              out.println("&lt;/body&gt;");
              out.println("&lt;/html&gt;");
              out.close();
          }
      }
  
  
      private void createServlet(String generatedKey, ServletContext servletContext) {
          String servletMapping = "/"+generatedKey;
  
   ServletRegistration sr = servletContext.addServlet(generatedKey, "com.path.lbs.servlets.testDynamic");
  
          sr.setInitParameter("keyname", generatedKey);
          sr.addMapping(servletMapping);
  
      }
  </code></pre>
  
  <p>I get the following error.</p>
  
  <blockquote>
    <p>java.lang.IllegalStateException:
    PWC1422: Unable to configure mapping
    for servlet 1114600676 of servlet
    context /123-LBS, because this servlet
    context has already been initialized</p>
  </blockquote>
  
  <p>Is it impossible to add new servlets at runtime i.e. after the Servlet Context is initialised or am I doing something wrong?</p>