Do I really need web.xml for a Servlet based Java web application? Do I really need web.xml for a Servlet based Java web application? java java

Do I really need web.xml for a Servlet based Java web application?


You don't need a web.xml file if you have a container that supports the latest j2ee specs.Here is a link to an simple servlet example that use an annotation and here you can find the same for Spring MVC; I post the example here for you convenience

public class MyWebApplicationInitializer implements WebApplicationInitializer {    @Override    public void onStartup(ServletContext container) {        ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet());        registration.setLoadOnStartup(1);        registration.addMapping("/example/*");    }}

Here is another link that show how to use the other annotations available(@ServletFilter, @WebServletContextListener); you can download the specs form here in order to get a more detailed view of the annotations available via j2ee.


Starting in Servlet 3, no web.xml is required. You're going to want to use something like Tomcat 7 or 8 (better choice). For raw servlets this is a good starting point.

If you want to use modern Spring, Grails 3 is a great way to go. It side steps all of these issues and Grails is a very productive framework for web development. You can think of it as Ruby on Rails built on top of Spring and Hibernate.

At this point, you shouldn't have to write any web.xml to get set up unless you use a framework that needs it. I don't know about spring mvc, but Grails doesn't require you to do that and it uses most of what you're already used to using.


Another way (Spring 3.1+) -

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[] { "/" };    }}