0.写在前面,展示一下所出现的问题
-
客户端错误状态
-
后台服务器错误信息,tomcat Log如下:
ClassNotFoundException:org.springframework.web.servlet.DispatcherServlet
1.查看maven项目的pom.xml配置是否正确
- 是否在项目中已经导入了spring-context等对应的坐标,略(一般没问题)
- 是否正确导入了maven的插件,略(一般没问题)
- 项目的执行流程,即各控制器在项目中所起的作用,如图
2. 查看项目的web.xml配置是否正确
-
配置核心控制器 Servlet,即:前端控制器DispatcherServlet
-
如果ctrl+鼠标单击可以看到源码,即配置正确
-
是否在项目启动时就加载spingmvc的配置文件,配置为应用启动时就加载
-
配置文件springmvc.xml的位置是否配置正确,我的文件放在resources的一层目录下,所以直接跟在classpath后就ok
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
- 给出完整代码,方便使用
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- SpringMVC的核心控制器 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置初始化参数,用于读取 SpringMVC 的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 配置 servlet 的对象的创建时间点:应用加载时创建。
取值只能是非 0 正整数,表示启动顺序 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
- 查看你的web项目下是否已经显示了dispatcherServlet,如果有,那么ok
3. 对应的 spring mvc 的配置文件是否正确
- 配置文件中头文件中需要的组件以及约束是否添加正确(这里给出代码方便复制)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
- 是否已经开启spring注解扫描
<!--开启spring注解扫描-->
<context:component-scan base-package="pers.pluto"/>
- 注意视图解析器对象配置,这里的prefix和suffix属性分别对应路径名和后缀名(你要将页面跳转到哪里的哪个文件)
<!--视图解析器对象-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
- 是否开启springmvc框架注解支持,开启之后,你的RequestMapping注解才可以使用
<!--开启springmvc框架注解支持-->
<mvc:annotation-driven/>
4.查看下web项目是否部署正确
-
web的war包以及读取的web.xml文件位置是否正确
-
tomcat上部署项目
5.我的最终解决方案
-
假如上边所有步骤都正确,依然报这个错误java.lang.ClassNotFoundException:org.springframework.web.servlet.DispatcherServlet;那么,可能我们遇到了同一种非常罕见的错误,解决其实很简单
-
首先打开Prpject Structure–>Artifacts,点开WEB-INF可以发现少了点东西,少了这个存放jar包lib文件夹
-
所以我们手动导入这个lib
-
完成上一步操作可以看到lib文件夹出现了
-
再次启动tomcat,不再抛出异常,OK,大功告成
-
因为自己由于被这个问题困扰了一整天,写这篇博客希望可以帮到你,如有发现有错误,欢迎随时交流,共同学习。