springboot的maven多子模块项目整合jsp报错详解
根据我之前的一篇blog:使用idea整合 spring boot 和jsp详细教程,这篇博客针对的是一个不包含子项目的spring boot maven项目,当项目中只有一个父项目时,上述教程可是正常的访问到jsp页面,但是当你在子项目中创建module并添加maven依赖,添加jsp并启动项目时,系统无法找到页面并报404;本教程就是告诉大家如何在spring boot的maven子项目中整合jsp页面;
- 第一步:创建目录结构:
我就使用之前的工程了(springboot +spring cloud+eureka+fegin的工程,这里就不再单独创建一遍了,如果大家手头没有,请看这里:springboot2.0+spring cloud+eureka(分布式项目)项目搭建详细教程(附加源码))
创建好的工程目录结构如下:
咱们以consumser这个子项目来整合jsp,consumer这个项目的maven依赖如下:
以下依赖只有spring-boot-starter-web这个依赖是必须的,如果你不整合cloud+fegin,其他依赖都是没有用的,当然你也可以创建一个spring boot工程,并创建consumer这个module,然后添加上spring-boot-starter-web这个依赖,这也是完全可以的;
<dependencies>
<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>
</dependency>
<!--注意:spring boot对jsp的支持不是很好,在使用spring boot自带tomcat的同时,还需要引入另外的一个tomcat,以来如下所示,且scope属性需要被注释掉 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId> <!--<scope>provided</scope> 注意,这个scope需要被注释掉-->
</dependency>
<!-- springboot+springcloud+eureka+fegin相关依赖 -->
<dependency>
<groupId>com.example</groupId>
<artifactId>entity</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
- 第二步:创建Controller,jsp页面,并修改yml配置文件:
controller如下,一个非常简单的controller,使用@Controller注解,并返回到index页面:jsp如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Full Layout - jQuery EasyUI Demo</title>
</head>
<body>
<input type="button" value="点我" />
<input type="text" style="height:100px;width:90%" id="input"/>
</body>
</html>
jsp的目录结构如下,同Java、resources同级,创建webapp/WEB-INF/jsp/index.jsp文件:
yml配置文件只需要添加一下jsp的前缀和后缀即可:
- 第三步:启动项目 并访问,访问后结果如下:
根据以上图片可以看到系统访问到controller,但是并没有找到jsp页面,既然是404错误,那么肯定是jsp页面的路径不对喽,咱们先假定spring boot的子项目找的路径也是父目录对应的路径,即将webapp目录由子模块移动到父模块中;然后在启动查看是否能访问;如下图:
启动项目并访问,结果发现不是这么回事,这种方法也不好使:
** 第四步:正确找到该路径;
我们唯一可以确定的是,页面报404错误的原因是找不到jsp页面的路径,或者说路径错误,在只有一个父模块的项目中,咱们能正常找到jsp,在含有子模块的项目中就找不到路径,很明显的说咱们需要修改web层访问的路径,怎么修改呢,这里要用到一个配置类:具体如下:**
@Configuration
public class GlobalConfig {
@Bean
public WebServerFactoryCustomizer<TomcatServletWebServerFactory> customizer() {
return (factory) -> {
factory.addContextCustomizers((context) -> { //模块中webapp相对路径
//consumer为你子项目的module名称,而不是你修改的application name这点需要注意;
String relativePath = "consumer/src/main/webapp";
File docBaseFile = new File(relativePath); // 如果路径不存在,则把这个路径加入进去
if (docBaseFile.exists()) {
context.setDocBase(docBaseFile.getAbsolutePath());
}
});
};
}
}
启动并访问成功: