您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# SpringBoot项目如何整合JSP
## 前言
SpringBoot默认推荐使用Thymeleaf等模板引擎,但在某些遗留项目或特定需求场景下,仍需整合传统的JSP(JavaServer Pages)。本文将详细介绍如何在SpringBoot 2.x项目中整合JSP视图技术。
---
## 一、环境准备
### 1. 创建项目
通过Spring Initializr创建项目时需注意:
```xml
<!-- 必须选择War包打包方式 -->
<packaging>war</packaging>
<!-- servlet依赖 -->
<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>
<scope>provided</scope>
</dependency>
<!-- JSTL标签库(可选) -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
在application.properties
中添加:
# 视图前缀和后缀
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
# 开发时关闭缓存
spring.jsp.servlet.init-parameters.development=true
必须手动创建以下目录:
src
└── main
├── java
├── resources
└── webapp
└── WEB-INF
└── views # JSP存放目录
@Controller
public class DemoController {
@GetMapping("/hello")
public String hello(Model model) {
model.addAttribute("message", "Hello JSP!");
return "demo"; // 对应/WEB-INF/views/demo.jsp
}
}
/WEB-INF/views/demo.jsp
:
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Demo</title>
</head>
<body>
<h1>${message}</h1>
<c:if test="${not empty message}">
<p>Message exists!</p>
</c:if>
</body>
</html>
spring.mvc.view.prefix
配置webapp/WEB-INF
下确保依赖正确且添加了:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
在IDEA中:
1. 打开Run/Debug Configurations
2. 勾选Build project automatically
3. 添加compiler.automake.allow.when.app.running
注册表项
mvn package
生成war包部署到外部Tomcatspring-boot-starter-tomcat
替代嵌入式容器虽然现代项目更推荐使用Thymeleaf/Vue等前后端分离方案,但在特定场景下整合JSP仍有其价值。通过本文的配置指南,开发者可以快速实现SpringBoot与JSP的整合。建议新项目优先考虑更现代的视图技术,老项目迁移时可参考此方案逐步重构。 “`
注:实际使用时请根据SpringBoot版本调整依赖版本号,本文示例基于SpringBoot 2.7.x版本编写。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。