介绍
虽然Spring Boot推荐使用Thymeleaf作为模板引擎,但由于早期大量Spring MVC项目都是使用JSP作为视图页面的,因此Spring Boot依然为JSP提供了支持,真正支持JSP的并不是Spring Boot ,而是Spring MVC, 因此Spring Boot 只要为SpringMVC的Servlet(JSP的本质)提供自动配置支持,就会自动支持JSP。
集成方法
-
src/main 下和java与resourcs同级创建一个 webapp 目录,web项目正常webapp文件夹图中会显示出来的蓝点且右键可以创建jsp文件,如果没有可以通过下图设置
-
新建webapp/WEB-INF文件夹(最好加WEB-INF,这样打包后的jsp代码是在其下面安全些),下面可以建子目录和jsp文件,
-
主要涉及源码WebMvcProperties-配置View的prefix和suffix属性,InternalResourceViewResolver-内部资源视图解析器
-
pom.xml引入依赖添加build配置
jar包
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
/dependency>
build配置
<build>
<resources>
<resource>
<!--源文件位置-->
<directory>src/main/webapp</directory>
<!--指定编译到META-INF/resources,该目录不能随便写-->
<targetPath>META-INF/resources</targetPath>
<!--指定要把哪些文件编译进去,**表示webapp目录及子目录,*.*表示所有文件-->
<includes>
<include>**/*.*</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
</build>
- 后端代码
- 演示
- 其他扩展
(1)JSP使用WebMvcProperties做配置,视图解析类:InternalResourceViewResolver extends UrlBasedViewResolver extends AbstractCachingViewResolver extends WebApplicationObjectSupport extends ApplicationObjectSupport implements ApplicationContextAware
(2)Thymeleaf使用ThymeleafProperties做配置,视图解析类:ThymeleafViewResolver extends AbstractCachingViewResolver extends WebApplicationObjectSupport extends ApplicationObjectSupport implements ApplicationContextAware
(3)FreeMarker使用FreeMarkerProperties做配置,视图解析类:FreeMarkerViewResolver extends AbstractTemplateViewResolver extends UrlBasedViewResolver extends AbstractCachingViewResolver extends WebApplicationObjectSupportextends ApplicationObjectSupport implements ApplicationContextAware
(4)注意上面这几个类都实现了ApplicationContextAware接口,spring容器启动加载bean时会自动调该接口的setApplicationContext方法,可以使用该方法获得ApplicationContext容器对象。
(5)Thymeleaf默认prefix值为classpath:/templates/,suffix值为.thml,
(6)FreeMarker默认prefix值为classpath:/templates/,suffix值为.ftlh