文章目录
spring-boot启用jsp
1.pom文件引入相关依赖
<!-- 添加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>
2.pom文件引入springboot启动插件
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
1.正常用idea启动springboot入口函数,无法加载jsp相关jar包,http报404错;
2.使用springboot的maven插件,idea中maven中插件中,可以双击启动项目;
spring-boot打war包
1.开发完成,需要打包测试,如果打包成jar,同样jsp无法渲染出。
2.需要打包成war,并且能够加载出jsp相关jar包。
1.pom中配置打包后,启动类入口
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.xxx.service.xx.Application</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
2.pom中配置打包资源目录信息
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/webapp/</directory>
<!--注意此次必须要放在此目录下才能被访问到 -->
<targetPath>META-INF/resources</targetPath>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
3.启动类配置,继承SpringBootServletInitializer
@EnableDiscoveryClient
public class Application extends SpringBootServletInitializer {
...
@Override// 兼容jsp 404
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
...
}
spring-boot项目jar/war包启动,使用内部资源
1.成功打包启动服务后,获取项目中webapp中的文件,由于启动的是未解压的war包,Linux/windows系统,无法加载非自盘目录文件,从而无法获取到对应资源文件信息。
2.服务启动错误信息
file:/opt/xxxxx.war!/WEB-INF/classes!/resource/img/axx_1/qrcodeerror.png
3.不能获取jar中的文件,可以使用文件流对象
log.info("【jspConfig.getQrErrorImage】:{}", jspConfig.getQrErrorImage());
InputStream is = this.getClass().getResourceAsStream(jspConfig.getQrErrorImage());
4.资源文件外置
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//需要配置1:----------- 需要告知系统,这是要被当成静态文件的!
//第一个方法设置访问路径前缀,第二个方法设置资源路径
registry.addResourceHandler("*.js", "*.html", "*.css", "*.ttf", "*.woff",
"*.woff2", "*.jpg", "*.png", "*.gif", "*.ico")
.addResourceLocations("classpath:/static/");
}
}