一、pom.xml引入依赖
<!--JSP的springBoot必须是War包-->
<packaging>war</packaging>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 添加servlet依赖模块 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- 添加jstl标签库依赖模块 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!--添加tomcat依赖模块.-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- 使用jsp引擎,springboot内置tomcat没有此依赖 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
二、在application.properties中配置
#spring 视图配置
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
三、创建controller进行访问
@Controller
public class IndexController {
// 添加index接口
@RequestMapping("/index")
public String index(ModelMap map){
map.put("title", "HelloWorld");
System.out.println("请求index接口");
return "index";
}
}
四、解决在Intellij Idea项目中无法新建jsp文件问题
点击File-Project Structrue,选择Modules,展开项目下的web,如下图
点击右下的+号,在弹出的窗口指定你的项目资源路径,这里直接点确定就好了
保存退出,现在可以在项目中的任何一个地方建jsp文件了
五、解决springboot集成jsp找不到页面
5.1、方式一:修改working directory
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BfviKFFS-1589525258789)(D:\work\exu-gitee\mybook\assets\springboot-jsp.png)]
5.2、方式二:添加一个配置文件
@Configuration
public class GlobalConfig {
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> customizer() {
return (factory) -> {
factory.addContextCustomizers((context) -> {
//模块中webapp相对路径
String relativePath = "springboot-jsp/src/main/webapp";
File docBaseFile = new File(relativePath);
// 路径是否存在
if (docBaseFile.exists()) {
context.setDocBase(docBaseFile.getAbsolutePath());
}
}
);
};
}
}