SpringBoot不推荐使用jsp,因为jsp在编译的时候先翻译成.java文件,然后再编译成.class文件,运行的时候就是一个servlet的.class文件,比较重量级,所以推荐使用freemarker,因为freemarker在运行的时候就是静态资源
0、创建SpringBoot的web项目
1、引入JSP依赖包
<dependencies>
<!-- SpringBoot整合web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--引入了Spring Boot默认的HTTP引擎Tomcat-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- servlet依赖的jar包start -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- jsp依赖jar包 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!--jstl标签依赖的jar包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
<!-- 打包时将jsp文件拷贝到META-INF目录下 -->
<resource>
<!-- 指定resources插件处理哪个目录下的资源文件 -->
<directory>src/main/webapp</directory>
<!--注意此次必须要放在此目录下才能被访问到 -->
<targetPath>META-INF/resources</targetPath>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
</build>
2、配置SpringBoot的配置文件
推荐一个yml与properties互转的在线工具:yml与properties在线互转
如果是properties文件,配置如下内容
#页面默认前缀目录
spring.mvc.view.prefix=/WEB-INF/jsp/
#页面默认后缀目录
spring.mvc.view.suffix=.jsp
此处使用yml文件,所以在yml文件配置如下内容
spring:
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
3、创建Controller,写一个方法用于请求访问,同时给前端传值
@Controller
public class JspController {
@RequestMapping(value = "tojsp")
public String toJsp(Map<String,Object> map){
map.put("jsp","SpringBoot集成JSP,后端给前端传值渲染页面");
return "hello";
}
}
4、创建jsp文件
在main的下级目录,和Java、resources同级目录创建webapp文件夹,并依次创建WEB-INF和jsp,在jsp文件夹中创建hello.jsp;在WEB-INF文件夹中创建web.xml文件
web.xml文件内容
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
</web-app>
5、启动项目访问