Spring MVC and Servlets 3.0 - Do you still need web.xml?

前端 未结 2 1770
眼角桃花
眼角桃花 2020-12-13 04:28

In a typical Spring MVC web app, you would declare the DispatcherServlet in web.xml like so




        
2条回答
  •  星月不相逢
    2020-12-13 04:59

    Yes you don't need web.xml to startup your webapp Servlet 3.0+. As Alex already mentioned you can implement WebApplicationInitializer class and override onStartup() method. WebApplicationInitializer is an interface provided by Spring MVC that ensures your implementation is detected and automatically used to initialize any Servlet 3 container.

    Is there a way to configure your full Spring application without any xml?

    Adding this answer just to add another way. You don't need to implement WebApplicationInitializer. An abstract base class implementation of WebApplicationInitializer named AbstractDispatcherServletInitializer makes it even easier to register the DispatcherServlet by simply overriding methods to specify the servlet mapping and the location of the DispatcherServlet configuration -

    public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {
    
        @Override
        protected WebApplicationContext createRootApplicationContext() {
            return null;
        }
    
        @Override
        protected WebApplicationContext createServletApplicationContext() {
            XmlWebApplicationContext cxt = new XmlWebApplicationContext();
            cxt.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
            return cxt;
        }
    
        @Override
        protected String[] getServletMappings() {
            return new String[] { "/" };
        }
    
    }
    

提交回复
热议问题