Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

java - Adding a dynamic servlet using servlet 3.0 throws exception

I need to create add servlets at runtime. When I run the following 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("<html>");
            out.println("<head>");
            out.println("<title> URI out</title>");
            out.println("</head>");
            out.println("<body>");
            Integer generatedKey = Math.abs(randomiser.nextInt());
            out.print(generatedKey);

            createServlet(Integer.toString(generatedKey),request.getServletContext());

        } finally {
            out.println("</body>");
            out.println("</html>");
            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);

    }

I get the following error.

java.lang.IllegalStateException: PWC1422: Unable to configure mapping for servlet 1114600676 of servlet context /123-LBS, because this servlet context has already been initialized

Is it impossible to add new servlets at runtime i.e. after the Servlet Context is initialised or am I doing something wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Is it impossible to add new servlets at runtime i.e. after the Servlet Context is initialised?

That's correct. You need to do it in ServletContextListener#contextInitialized().

@WebListener
public class Config implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent event) {
        // Do it here.
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        // ...
    }
}

However, for your particular functional requirement, a single controller servlet in combination with command pattern is much better suited. You could then add commands (actions) during runtime and intercept on it based on the request URI. See also my answer on Design Patterns web based applications for a kickoff.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...