我通过@Configuration类使用Spring MVC:
@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {
// more stuff
}
在我的web.xml中,我创建了ApplicationContext:
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>my.package.WebConfiguration</param-value>
</context-param>
我还创建了一个DispatcherServlet,如下所示:
<servlet>
<servlet-name>mywebapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mywebapp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
为了让dispatcherServlet工作,我需要一个mywebapp-servlet.xml现在,它是空的。我真的需要mywebapp-servlet.xml文件吗?
答案 0 :(得分:4)
您不需要任何XML文件。但是您必须告诉Dispatcher不要查找默认文件:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>my.pack.WebConfiguration</param-value>
</context-param>
<servlet>
<servlet-name>mywebapp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mywebapp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
仅供参考:事实上,在Servlet 3中也不再需要web.xml。