|
| 1 | +package com.baeldung.mvc.velocity.spring.config; |
| 2 | + |
| 3 | +import java.util.Set; |
| 4 | + |
| 5 | +import javax.servlet.ServletContext; |
| 6 | +import javax.servlet.ServletException; |
| 7 | +import javax.servlet.ServletRegistration; |
| 8 | + |
| 9 | +import org.springframework.web.WebApplicationInitializer; |
| 10 | +import org.springframework.web.context.ContextLoaderListener; |
| 11 | +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; |
| 12 | +import org.springframework.web.context.support.GenericWebApplicationContext; |
| 13 | +import org.springframework.web.servlet.DispatcherServlet; |
| 14 | + |
| 15 | +public class MainWebAppInitializer implements WebApplicationInitializer { |
| 16 | + |
| 17 | + /** |
| 18 | + * Register and configure all Servlet container components necessary to |
| 19 | + * power the web application. |
| 20 | + */ |
| 21 | + @Override |
| 22 | + public void onStartup(final ServletContext sc) throws ServletException { |
| 23 | + |
| 24 | + // Create the 'root' Spring application context |
| 25 | + final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); |
| 26 | + root.register(WebConfig.class, SpringConfig.class); |
| 27 | + |
| 28 | + // Manages the lifecycle of the root application context |
| 29 | + sc.addListener(new ContextLoaderListener(root)); |
| 30 | + |
| 31 | + // Handles requests into the application |
| 32 | + final ServletRegistration.Dynamic appServlet = sc.addServlet("mvc", |
| 33 | + new DispatcherServlet(new GenericWebApplicationContext())); |
| 34 | + appServlet.setLoadOnStartup(1); |
| 35 | + |
| 36 | + final Set<String> mappingConflicts = appServlet.addMapping("/"); |
| 37 | + if (!mappingConflicts.isEmpty()) { |
| 38 | + throw new IllegalStateException("'appServlet' could not be mapped to '/' due " |
| 39 | + + "to an existing mapping. This is a known issue under Tomcat versions " |
| 40 | + + "<= 7.0.14; see https://issues.apache.org/bugzilla/show_bug.cgi?id=51278"); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | +} |
0 commit comments