Okto
Okto

Reputation: 367

How to programmatically add MULTIPLE servlets in Java EE

How can i map multiple Servlets 3.0 programmatically (not using deployment descriptor web.xml)

What i have is folling code which works great... but i could not found any way about adding/mapping more than one servlet to an url-pattern:

@WebListener
public class NewServletListener implements ServletContextListener {

@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext sc = sce.getServletContext();
    ServletRegistration sr = sc.addServlet("test", "BusinessObjects.test");  
    sr.addMapping("/test"); 
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}

What i need is some kind of this:

ServletRegistration sr = sc.addServlet("testA", "BusinessObjects.testA");  
sr.addMapping("/testA"); 

ServletRegistration sr2 = sc.addServlet("testB", "BusinessObjects.testB");  
sr2.addMapping("/testB"); 

ServletRegistration sr3 = sc.addServlet("testC", "BusinessObjects.testC");  
sr3.addMapping("/testC");

and so on...

but this way does not work, i event tried an array... what im doing wrong?

thank you so much for help

Upvotes: 2

Views: 3085

Answers (1)

tmarwen
tmarwen

Reputation: 16374

You should use the javax.servlet.ServletRegistration.Dynamic to register your servlets not ServletRegistration so the code might look as below:

@WebListener
public class MyContextListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent event) {
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
            ServletContext context = event.getServletContext();

            Dynamic dynamic = context.addServlet("ServletA", ServletA.class);
            dynamic.addMapping("/ServletA");

            Dynamic dynamic2 = context.addServlet("ServletB", ServletB.class);
            dynamic2.addMapping("/ServletB");
    }

}

And you will have both ServletA and ServletB registered programatically.

BR.

Upvotes: 5

Related Questions