You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 2内嵌Tomcat部署含JSP的外部WAR时类找不到求助

内嵌Tomcat部署含JSP的外部WAR文件报错解决

问题背景

生产环境运行基于Spring Boot 2的内嵌Tomcat应用,需在同一Tomcat实例中部署另一个包含JSP元素的WAR文件。已按相关方案添加以下依赖:

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>

同时在Bean中配置Web应用上下文:

Context context = tomcat.addWebapp(contextPath, path);
context.setParentClassLoader(getClass().getClassLoader());

但外部WAR启动失败,抛出如下异常:

SEVERE:Servlet[jsp] in web application /test threw load exception
java.lang.ClassNotFoundException: org.apache.jasper.servlet.jspServlet

解决方案

问题核心是Spring Boot的依赖管理中,tomcat-embed-jasper默认被设置为provided范围,该范围下依赖不会被打包到生产环境的JAR包中,导致运行时缺失Jasper Servlet类。

调整依赖范围

显式将tomcat-embed-jasper的依赖范围设置为compile,确保它被包含在最终构建产物里:

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>

避免类加载冲突(可选)

如果待部署的外部WAR自身依赖了Tomcat的JSP相关组件(如tomcat-jasper),建议在引入该WAR依赖时排除这些组件,避免类加载冲突:

<dependency>
    <groupId>你的WAR包groupId</groupId>
    <artifactId>你的WAR包artifactId</artifactId>
    <type>war</type>
    <exclusions>
        <exclusion>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jasper</artifactId>
        </exclusion>
    </exclusions>
</dependency>

完成上述配置后,重新打包并启动Spring Boot应用,外部WAR的JSP Servlet即可正常加载运行。

内容的提问来源于stack exchange,提问作者Seeker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 08:08:12