Close

Spring MVC - DispatcherServlet Examples

Spring MVC 

    @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




    @Override
protected FrameworkServlet createDispatcherServlet (WebApplicationContext wac) {
DispatcherServlet ds = new DispatcherServlet(wac);
//setting this flag to true will throw NoHandlerFoundException instead of 404 page
ds.setThrowExceptionIfNoHandlerFound(true);
return ds;
}




    @Override
protected FrameworkServlet createDispatcherServlet (WebApplicationContext wac) {
DispatcherServlet ds = new DispatcherServlet(wac);
ds.setDetectAllHandlerExceptionResolvers(false);
return ds;
}




public class MyWebInitializer implements WebApplicationInitializer {

@Override
public void onStartup (ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx =
new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
ctx.setServletContext(servletContext);

ServletRegistration.Dynamic servlet =
servletContext.addServlet("springDispatcherServlet",
new DispatcherServlet(ctx));

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




See Also