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

Spring无法找到JSP文件,已尝试多种配置仍未解决

Spring Boot 返回JSP时404白标错误排查与解决

返回JSP文件时遭遇白标错误页,Spring无法定位到JSP文件。已尝试多种常规方案但问题仍未解决:

尝试过的操作

  • 将JSP文件放在webapp/WEB-INF/views目录下
  • 在pom.xml中引入tomcat-embed-jasper依赖
  • 尝试添加@ResponseBody确认映射配置(注:此操作会导致直接返回字符串而非视图,反而可能引发问题)

控制器代码

@Controller
public class sayHelloContainer {

    @RequestMapping("/hello")
    public String hello() {
        return "hello";
    }
}

报错信息

"Path with \"WEB-INF\" or \"META-INF\": [webapp/WEB-INF/views/hello.jsp]"
Resource not found
Exiting from "FORWARD" dispatch, status 404

application.properties配置

spring.mvc.view.prefix=/webapp/WEB-INF/views/
spring.mvc.view.suffix=.jsp
logging.level.org.springframework=debug

文件结构

src/main目录下包含java、resources、webapp三个子目录,JSP文件位于webapp/WEB-INF/views/hello.jsp

pom.xml依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

问题根源与解决方案

  1. 视图前缀配置错误
    spring.mvc.view.prefix 不应包含/webapp/——webapp是Web应用的根目录,Spring会自动从该目录下查找资源。修改为:

    spring.mvc.view.prefix=/WEB-INF/views/
    
  2. tomcat-embed-jasper依赖范围问题
    若使用内嵌Tomcat运行项目,provided范围会导致依赖在运行时无法加载,将其改为compile:

    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>compile</scope>
    </dependency>
    
  3. 移除@ResponseBody注解
    控制器方法返回视图名称时,不能添加@ResponseBody,否则Spring会将返回的字符串直接作为响应内容,而非查找对应JSP视图。确保控制器仅使用@Controller注解,方法无@ResponseBody。

  4. 确认打包方式
    检查pom.xml中是否设置打包方式为war,JSP仅在war包结构下能被正确识别:

    <packaging>war</packaging>
    

内容的提问来源于stack exchange,提问作者Aditya Kumar Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:25:45