ClassCastException: DispatcherServlet cannot be cast to Servlet

后端 未结 4 925
囚心锁ツ
囚心锁ツ 2020-12-31 10:13

I have created a new Spring MVC project using maven-eclipse and the following error is thrown:

(I tried some solutions from the stackoverflow which is not working i

相关标签:
4条回答
  • 2020-12-31 11:08

    Keep scope as 'provided' and try keeping that jar in tomcat/lib folders. This is because of each class loader of respective war tries to load its own Servlet-api classes separately,compared to application class loader which loads the Servlet-api classes at container level.

    So if u can make the jar moved to CATALINA_HOME/lib.you have required set of classes loaded by application class loader only and same version will be referred across by all wars.

    scope 'provided' conveys to class loader at war level that the classes required for this is already loaded by application class loader and insists class loader at its war level may not required to create separate instances or version for it that cause class cast exception

    0 讨论(0)
  • 2020-12-31 11:12

    In your case, ClassCastException seems to be because of classes being loaded by different classloaders. Say, you have the servlet-api.jar included by mistake in your WEB-INF/lib and you had set PARENT_LAST true for your webapp class loader. If you are running on an application server like WAS, this would mean you are loading interface with one class loader (some class loader at the top) and implementation (servlet-api jar just an e.g.) with another class loader at the bottom.

    0 讨论(0)
  • 2020-12-31 11:15

    Which application server you are using? I think Servlet jars files should be provide by your application srver.

    0 讨论(0)
  • 2020-12-31 11:20

    Change

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>compile</scope>
    </dependency>
    

    to

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
    

    provided has this description:

    This is much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.

    from the maven docs. You're basically telling Maven to provided the jar for compilation, but, at runtime, use some other, the servlet container's, jar.

    0 讨论(0)
提交回复
热议问题