Springboot项目对jsp页面的支持

397 阅读1分钟

Springboot项目对jsp页面的支持

1、前言

Springboot项目的和maven项目的结构有所不同,如图:

  • springboot项目在resources下面有两个包:static,templates,但是maven项目下没有。
  • springboot项目在src下的main文件夹是空的,但是maven项目下有一个webapp包以及webapp下的文件结构

springboot推荐使用模板引擎比如:thymeleaf。thymeleaf的默认配置就在templates文件下,仿照模板引擎,将jsp页面放在templates下是否可行呢,我们来一步一步验证。

2、添加依赖

springboot并没有直接对jsp做支持,需要因为tomcat对jsp的依赖:

<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>
    <!-- 编译时使用  可以是使用本地tomcat启动,否则就会冲突-->
    <scope>provided</scope>
</dependency>
<!-- tomcat对jsp的支持 -->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>
<!-- jsp依赖的工具 -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>

官方文档里有示例:

 JSP sample pom.xml

3、 验证templates下放置页面,配置是否可行

启动查看:

 跳转的结果来看,classpath被当成了文件夹,故无法指定jsp页面的位置。

4、参考官方demo

 从官方示例中可以看出,需要我们新建一个webapp文件夹。

 经过更改,页面就可以正常跳转了。

5、注意事项

  • 跳转jsp页面的时候,经常是会发生页面直接下载,这是因为没有对jsp的支持引入依赖:
<!-- tomcat对jsp的支持 -->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <scope>provided</scope>
</dependency>
<!-- jsp依赖的工具 -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>
  • 使用本地tomcat启动springboot项目报错,是因为springboot项目内置tomcat和本地的冲突导致的,需要指定内置tomcat为作用范围,编译时使用,就能兼容本地tomcat启动和内置tomcat启动:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <!-- 编译时使用  可以是使用本地tomcat启动,否则就会冲突-->
    <scope>provided</scope>
</dependency>