Solve the error reporting problem of cannot be cast to javax. servlet. Filter

  • 2021-11-10 10:27:59
  • OfStack

cannot be cast to javax. servlet. Filter reported an error due to servlet-api. jar conflict

Use maven to develop web application, and report an error when starting:

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

Then output an error:


 Serious : Exception starting filter encodingFilter
java.lang.ClassCastException: org.springframework.web.filter.CharacterEncodingFilter cannot be cast
 to javax.servlet.Filter

The cause of the problem is that after server-: tomcat starts, all jar packets in tomcat/lib directory are read into memory first. If there are the same packets in WEB-INF/lib directory in the application program in webapps directory, it will not be loaded.

Similar problems can be caused between different versions of packages

The way to solve this problem is to use servlet-ap. jar < scope > Tag, servlet-api and jsp-api are used for compilation, but these two dependencies are not used for packaging

As follows:


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

< dependency > Medium < scope > Which mainly manages dependent deployments. At present < scope > You can use five values:

* compile, the default, applies to all phases and will be released with Project 1.
* provided, similar to compile, expects JDK, container, or consumer to provide this dependency. Such as servlet. jar.
* runtime, used only at runtime, such as the JDBC driver, for both run and test phases.
* test, used only during testing, for compiling and running test code. Will not be published with the project.
* system, similar to provided, needs to explicitly provide jar with dependencies, and Maven does not look for it in Repository.

The above is the solution to the error report of cannot be cast to javax.servlet.Filter. Continue to sort out relevant knowledge in the follow-up. Thank you for your support to this site!


Related articles: