My Application Could not open ServletContext resource
Quote from the Spring reference doc:
Upon initialization of a DispatcherServlet, Spring MVC looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and creates the beans defined there...
Your servlet is called spring-dispatcher
, so it looks for /WEB-INF/spring-dispatcher-servlet.xml
. You need to have this servlet configuration, and define web related beans in there (like controllers, view resolvers, etc). See the linked documentation for clarification on the relation of servlet contexts to the global application context (which is the app-config.xml
in your case).
One more thing, if you don't like the naming convention of the servlet config xml, you can specify your config explicitly:
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
If you are getting this error with a Java configuration, it is usually because you forget to pass in the application context to the DispatcherServlet
constructor:
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher",
new DispatcherServlet()); // <-- no constructor args!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
Fix it by adding the context as the constructor arg:
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher",
new DispatcherServlet(ctx)); // <-- hooray! Spring doesn't look for XML files!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
Make sure your maven war plugin block in pom.xml includes all files (especially xml files) while building the war. But you don't need to include the .java files though.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.5</version>
<configuration>
<webResources>
<resources>
<directory>WebContent</directory>
<includes>
<include>**/*.*</include> <!--this line includes the xml files into the war, which will be found when it is exploded in server during deployment -->
</includes>
<excludes>
<exclude>*.java</exclude>
</excludes>
</resources>
</webResources>
<webXml>WebContent/WEB-INF/web.xml</webXml>
</configuration>
</plugin>