i need create add servlets @ runtime. when run 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()); } { 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 following error.
java.lang.illegalstateexception: pwc1422: unable configure mapping servlet 1114600676 of servlet context /123-lbs, because servlet context has been initialized
is impossible add new servlets @ runtime i.e. after servlet context initialised or doing wrong?
is impossible add new servlets @ runtime i.e. after servlet context initialised?
that's correct. need in servletcontextlistener#contextinitialized()
.
@weblistener public class config implements servletcontextlistener { @override public void contextinitialized(servletcontextevent event) { // here. } @override public void contextdestroyed(servletcontextevent event) { // ... } }
however, particular functional requirement, single controller servlet in combination command pattern better suited. add commands (actions) during runtime , intercept on based on request uri. see my answer on design patterns web based applications kickoff.
Comments
Post a Comment