Spring-boot运行jsp原理分析
结论:
分析过程如下:
编码阶段:
1、官方不推荐在spring-boot中使用jsp文件。
如果要使用,需要添加 jasper依赖:
< 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 >
2、配置文件属性
src/main/resources/application.properties配置文件
# 页面默认前缀目录
spring.mvc.view.prefix = /WEB-INF/jsp/
# 响应页面默认后缀
spring.mvc.view.suffix = .jsp
# 自定义属性,可以在Controller中读取
application.XXX =YYY
结构图如下
打包阶段
需要在pom中的build中增加如下属性,目的是将指定目录下的资源打包:
< resources >
<!-- 打包时将 jsp 文件拷贝到META-INF目录下-->
< resource >
<!-- 指定resources插件处理哪个目录下的资源文件 -->
< directory > src /main/ webapp </ directory >
<!--注意此次必须要放在此目录下才能被访问到-->
< targetPath > META-INF/resources </ targetPath >
< includes >
< include > **/** </ include >
</ includes >
</ resource >
< resource >
< directory > src /main/resources </ directory >
< includes >
< include > **/** </ include >
</ includes >
< filtering > false </ filtering >
</ resource >
</ resources >
启动并调试Fat-jar,分析源码
Jar包物理图:
Tomcat tomcat = new Tomcat();
File baseDir = ( this . baseDirectory != null ? this . baseDirectory : createTempDir( "tomcat" ));
\AppData\Local\Temp\tomcat.7897322053330749685.8080和tomcat-docbase.1385973521217649694.8080
初始目录中内容为空。
……
……
……
通过 Archive提供的 URL(如果 Archive中有子 Archive,可以通过第二个方法获取)。然后通过 Classloader提供的访问 classpath resource的能力来实现的。
jsp访问路径在之前的配置文件中:
spring.view.prefix: /WEB-INF/jsp/
provides: tomcat-embed-core
将jsp文件转换为java servlet文件,编译为class。