Spring Boot 集成 JSP:从零开始的详细教程
1. 创建 Spring Boot 项目
使用 Spring Initializr(start.spring.io)创建一个 Spring Boot 项目,选择“Web”作为依赖。
2. 添加 JSP 相关依赖
在 pom.xml 文件中添加以下依赖:
<!-- Servlet API -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <scope>provided</scope>
</dependency>
<!-- JSP 支持 -->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- JSTL 支持 -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>
同时,在 <build> 标签下添加以下配置:
<resources>
    <resource>
        <directory>src/main/webapp</directory>
        <targetPath>META-INF/resources</targetPath>
        <includes>
            <include>*.*</include>
        </includes>
    </resource>
</resources>
3. 配置视图解析器
在 application.properties 或 application.yml 文件中配置视图解析器:
properties复制
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
4. 创建 JSP 页面
在 src/main/webapp/WEB-INF/jsp/ 目录下创建一个 JSP 页面,例如 hello.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Hello</title>
</head>
<body>
    <h1>${message}</h1>
</body>
</html>
5. 编写 Controller
创建一个 Controller 类,用于处理请求并返回 JSP 页面:
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HelloController {
    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("message", "Hello, Spring Boot with JSP!");
        return "hello";
    }
}
6. 启动应用并测试
启动 Spring Boot 应用后,在浏览器中访问 http://localhost:8080/hello,应该能看到显示的 JSP 页面。
注意事项
- 
确保 JSP 文件放在 src/main/webapp/WEB-INF/jsp/目录下,这样 Spring Boot 才能正确加载。
- 
如果使用的是 Undertow 作为嵌入式 Servlet 容器,则不支持 JSP,必须使用 Tomcat。 
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号