idea报错:Allocate exception for servlet com.itheima.web.ServletDemo1

文章讲述了在Idea中运行Tomcat时遇到的Servlet配置错误,问题可能出在使用了不支持注解的Servlet版本或者依赖未正确设置为provided。解决方案包括在web.xml中配置Servlet,或者升级到支持注解的Servlet3.0及以上版本,以及确保servlet和jsp依赖的scope设为provided。
摘要由CSDN通过智能技术生成

问题描述

idea中运行tomcat时报错:

严重: Allocate exception for servlet com.itheima.web.ServletDemo1
java.lang.ClassCastException: com.itheima.web.ServletDemo1 cannot be cast to javax.servlet.Servlet

浏览器显示如下信息:
image.png

分析与解决

原因一:导入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>

原因二:导入servletjsp依赖时没有添加<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>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

在逃八阿哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值