Spring MVC项目报错:No WebApplicationContext found及配置问题求助
先帮你理清这两个问题的来龙去脉:
第一个错误的根源:No WebApplicationContext found
你遇到的这个异常,核心原因是直接访问的index.jsp不在DispatcherServlet的处理范围内——你的DispatcherServlet只映射了*.htm路径,但index.jsp是直接被容器处理的,没有经过DispatcherServlet,导致Spring的form标签(<form:form>)找不到WebApplicationContext。
为什么加了ContextLoaderListener后出现新问题?
ContextLoaderListener的作用是加载Spring的根WebApplicationContext,它默认会去寻找/WEB-INF/applicationContext.xml这个配置文件。你现在只配置了DispatcherServlet的上下文(nov-servlet.xml),没有根上下文的配置文件,所以会抛出找不到文件的异常。
那是不是必须写applicationContext.xml?答案是不一定,分两种情况处理:
情况1:不需要单独的根上下文(适合小型项目)
如果你的项目不需要拆分业务层/持久层的Bean和MVC层的Bean,完全可以去掉ContextLoaderListener,转而解决第一个错误的核心问题:让index.jsp能获取到WebApplicationContext。
解决办法有两个:
- 方法A:调整DispatcherServlet的映射路径
把web.xml里的servlet-mapping改成/(注意这会让DispatcherServlet处理所有请求,包括静态资源,后续需要配置静态资源的处理):<servlet-mapping> <servlet-name>nov</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> - 方法B:添加RequestContextListener
在web.xml里添加监听器,让非DispatcherServlet处理的请求也能访问到WebApplicationContext:
这样直接访问index.jsp时,Spring的form标签就能找到上下文了。<listener> <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class> </listener>
情况2:需要拆分上下文(适合中大型项目)
如果你的项目需要把业务Bean(比如Service、DAO)放在根上下文,MVC相关的Bean(Controller、ViewResolver)放在DispatcherServlet的上下文,那么可以保留ContextLoaderListener,但需要指定根上下文的配置文件路径,或者创建对应的配置文件:
- 方式1:指定自定义的根配置文件路径
在web.xml里添加context-param,告诉ContextLoaderListener去哪里找配置文件(比如你想复用现有的配置,或者指定多个文件):<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/nov-root.xml</param-value> <!-- 这里填你的根配置文件路径 --> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> - 方式2:创建空的applicationContext.xml
如果暂时没有根上下文的Bean需要配置,可以在/WEB-INF下创建一个空的applicationContext.xml,内容如下:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> </beans>
额外提示
你的index.jsp里的form标签action="search",如果保留*.htm的映射,记得把action改成search.htm,否则DispatcherServlet不会处理这个请求哦。
内容的提问来源于stack exchange,提问作者user3927150

