Close

Java Servlet - ServletRegistration.Dynamic Examples

Java Servlet JAVA EE 

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebListener;
import java.util.Locale;

@WebListener
public class AppContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
Locale locale = Locale.getDefault();
ServletRegistration.Dynamic registration = event.getServletContext()
.addServlet("appController", locale.getISO3Country().equals("USA") ?
DefaultAppController.class : OffshoreAppController.class);
registration.addMapping("/app/");

}

@Override
public void contextDestroyed(ServletContextEvent sce) {

}
}
Original Post




import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;


public class MyWebInitializer implements WebApplicationInitializer {

@Override
public void onStartup (ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx =
new AnnotationConfigWebApplicationContext();
//register our config class
ctx.register(MyWebConfig.class);

ctx.setServletContext(servletContext);

//using servlet 3 api to dynamically create
//spring dispatcher servlet
ServletRegistration.Dynamic servlet =
servletContext.addServlet("springDispatcherServlet",
new DispatcherServlet(ctx));

servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
Original Post




See Also