Skip to content

Instantly share code, notes, and snippets.

@jdmr
Created February 18, 2013 21:33
Show Gist options
  • Save jdmr/4980963 to your computer and use it in GitHub Desktop.
Save jdmr/4980963 to your computer and use it in GitHub Desktop.
Web application startup configuration
package org.davidmendoza.demo.config;
import org.sitemesh.config.ConfigurableSiteMeshFilter;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.*;
import java.util.EnumSet;
import java.util.Set;
public class StartUpConfig implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(ComponentConfig.class, DataConfig.class, MailConfig.class, WebConfig.class);
context.setDisplayName("DemoApp");
FilterRegistration.Dynamic sitemeshFilter = servletContext.addFilter("sitemeshFilter", new ConfigurableSiteMeshFilter());
sitemeshFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("characterEncodingFilter", new CharacterEncodingFilter());
characterEncodingFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
characterEncodingFilter.setInitParameter("encoding", "UTF-8");
characterEncodingFilter.setInitParameter("forceEncoding", "true");
servletContext.addListener(new ContextLoaderListener(context));
//servletContext.setInitParameter("defaultHtmlEscape", "false");
DispatcherServlet servlet = new DispatcherServlet();
// no explicit configuration reference here: everything is configured in the root container for simplicity
servlet.setContextConfigLocation("");
ServletRegistration.Dynamic appServlet = servletContext.addServlet("appServlet", servlet);
appServlet.setLoadOnStartup(1);
appServlet.setAsyncSupported(true);
Set<String> mappingConflicts = appServlet.addMapping("/");
if (!mappingConflicts.isEmpty()) {
throw new IllegalStateException("'appServlet' cannot be mapped to '/' under Tomcat versions <= 7.0.14");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment