Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

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

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

<!-- MVC Servlet -->
<servlet>
    <servlet-name>sample</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>sample</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Along with listeners, filters, etc.

With servlet-api 3.0, you can declare your servlets with the annotation @WebServlet instead of adding them to your web.xml. Spring 3.2 already has @Configuration and @EnableXYZ for its context configuration. Does it have something similar for the DispatcherServlet, ie. is there a way to configure your full Spring application without any xml?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With JEE6, if your application container is Servlet 3.0 ready what you need to do is:

  1. Create a custom class that implements ServletContainerInitializer (i.e. com.foo.FooServletContainer)
  2. Create a file in your META-INF/services folder named javax.servlet.ServletContainerInitializer which will contain the name of your implementation above (com.foo.FooServletContainer)

Spring 3 is bundled with a class named SpringServletContainerInitializer that implements the stuff above (so you don't need to create yourself the file in META-INF/services. This class just calls an implementation of WebApplicationInitializer. So you just need to provide one class implementing it in your classpath (the following code is taken from the doc above).

public class FooInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) {
        WebApplicationContext appContext = ...;

        ServletRegistration.Dynamic dispatcher =
           container.addServlet("dispatcher", new DispatcherServlet(appContext));
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");
    }
 }

That's it for the web.xml thing, but you need to configure the webapp using @Configuration, @EnableWebMvc etc..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...