问题描述
在idea
中运行tomcat
时报错:
严重: Allocate exception for servlet com.itheima.web.ServletDemo1
java.lang.ClassCastException: com.itheima.web.ServletDemo1 cannot be cast to javax.servlet.Servlet
浏览器显示如下信息:
分析与解决
原因一:导入servlet
依赖时导入了版本2,但配置访问路径时采用了注解的方式:@WebServlet("/demo1")
,而Servlet 从3.0版本后才开始支持使用注解配置,3.0版本前只支持 XML 配置文件的配置方式。
故解决方案有两种:
方案一:将@WebServlet("/demo1")
注释掉,在web.xml
中配置servlet
的全类名和访问路径:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--servlet 全类名-->
<servlet>
<servlet-name>demo1</servlet-name>
<servlet-class>com.itheima.web.ServletDemo1</servlet-class>
</servlet>
<!--servlet 访问路径-->
<servlet-mapping>
<servlet-name>demo1</servlet-name>
<url-pattern>/demo1</url-pattern>
</servlet-mapping>
</web-app>
方案二:将servlet
依赖替换成3.0之后的版本:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
原因二:导入servlet
和jsp
依赖时没有添加<scope>provided</scope>
,添加一下即可:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>