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

IntelliJ运行JSP文件时出现404错误(Java Web App)

解决方案

一、先修复mvn clean spring-boot:run启动失败问题

首先注意命令拼写:正确的启动命令是mvn clean spring-boot:run(你可能少写了冒号),如果还是启动失败,按以下步骤排查:

  • 对齐依赖版本:不要手动指定tomcat-embed相关依赖的版本,依托Spring Boot父依赖的版本管理来保证兼容性,POM配置示例:
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.15</version> <!-- 替换成你实际使用的Spring Boot版本 -->
        <relativePath/>
    </parent>
    
    <dependencies>
        <!-- Web基础依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- JSP核心依赖 -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope> <!-- 打包war时用provided,jar包运行时可去掉该scope -->
        </dependency>
        <!-- JSTL标签支持(如果用到) -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
    </dependencies>
    
  • 检查打包方式:如果打包为war包,需在POM中声明<packaging>war</packaging>,并添加Spring Boot的war插件:
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    
  • 清理依赖缓存:执行mvn clean install -U强制更新本地仓库依赖,再重新尝试启动命令。

二、修复JSP右键运行404问题

Spring Boot项目中不能直接右键JSP文件运行,必须通过项目启动后的请求映射访问,按以下步骤调整:

  • 规范JSP存放路径:将JSP文件放在src/main/webapp/WEB-INF/jsp目录下(若自定义路径需在配置中声明),避免直接放在webapp根目录。
  • 配置视图解析器:在application.properties或application.yml中添加JSP视图解析规则:
    spring.mvc.view.prefix=/WEB-INF/jsp/
    spring.mvc.view.suffix=.jsp
    
  • 添加Controller映射:编写简单的Controller关联JSP,示例:
    @Controller
    public class PageController {
        @GetMapping("/your-page")
        public String showPage() {
            return "your-page"; // 对应WEB-INF/jsp/your-page.jsp
        }
    }
    
    启动项目后,访问http://localhost:8080/your-page即可正常加载JSP。
  • 标记Web资源目录:在IntelliJ中右键src/main/webapp目录,选择Mark Directory as -> Web Resource Directory,确保IDEA识别该目录为Web资源根。

三、自定义Servlet关联JSP的排查点

如果你的Servlet需要跳转JSP,需确保:

  • 用@WebServlet注解标记Servlet,并指定映射路径:
    @WebServlet("/demo-servlet")
    public class DemoServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            req.getRequestDispatcher("/WEB-INF/jsp/demo.jsp").forward(req, resp);
        }
    }
    
  • 在Spring Boot启动类上添加@ServletComponentScan注解,让框架扫描并注册Servlet。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 15:15:24