Spring Boot 2.X整合JSP
虽然Spring Boot官方不推荐使用JSP技术,但是对于一些小公司或者ZF网站,还是有必要的。本文将简单介绍Spring Boot 2.X如何整合JSP实现快速开发。
新建项目
这里可以用 Spring Initializr 快速创建一个Spring Boot项目,修改打包方式位war:

或者修改pom.xml中的packaging属性为war:
<packaging>war</packaging>
添加依赖
pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
新建目录
新建src/main/webapp/WEB-INF/views目录用于存放jsp资源文件:

修改配置
修改application.yml / application.properties文件:
spring:
mvc:
view:
prefix: /WEB-INF/views/
suffix: .jsp
编写代码
- 创建
index.jsp:
<%--
Created by IntelliJ IDEA.
User: xudc
Date: 2018/12/11
Time: 21:24
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>Welcome,${name}!</h3>
This is a jsp page.<br/>
</body>
</html>
- 新建
controller
/**
* @author xudc
* @date 2018/12/11 21:19
*/
@Controller
public class IndexController {
@GetMapping("/")
public String index(Model model){
model.addAttribute("name","xudc");
return "index";
}
}
启动运行
- 配置外部Tomcat、Jetty等Web容器运行:

- 以Maven Plugins的spring-boot:run运行;
切换到对应目录,直接在命令行输入以下命令启动:
mvn spring-boot:run

访问测试
浏览器打开http://localhost:8080/:

OK.至此,Spring Boot 2就简单的实现对JSP的支持了。
这里还是推荐大家用Spring Boot 官方推荐的模板引擎,比如:thymeleaf、freemarker等.
完整代码
| Github | 码云 |
本文介绍了在Spring Boot 2.X中整合JSP的步骤,包括新建项目、添加依赖、配置目录、修改配置、编写代码、启动运行及访问测试。虽然Spring官方不推荐使用JSP,但在某些场景下仍然有其必要性。文章提供了一个快速入门的指南,并建议使用官方推荐的模板引擎如thymeleaf、freemarker。
645

被折叠的 条评论
为什么被折叠?



