1.在SpringBoot中使用jsp,需要在pom.xml文件中添加依赖
<!--引入Spring Boot内嵌的Tomcat对JSP的解析包-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- servlet依赖的jar包start -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- servlet依赖的jar包start -->
<!-- jsp依赖jar包start -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- jsp依赖jar包end -->
<!--jstl标签依赖的jar包start -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
只添加Spring Boot内嵌的Tomcat对JSP的解析包也可以正常运行,因为我后面可能会使用到jstl等,所以我全部添加。
(2)在application.properties配置文件中设置视图为jsp
(3)在src/main下建一个目录webapp,webapp底下创建jsp页面index.jsp
(4)配置pom.xml的resources,主要就是把项目编译到target目录地下,网上有人说不配置访问不到jsp页面,我测试一下,可以访问,为了后续正常,我还是配置一下。
代码如下:
<resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> </resource> <!--springboot使用的web资源要编译到META-INF/resources--> <resource> <directory>src/main/webapp</directory> <targetPath>META-INF/resources</targetPath> <includes> <include>**/*.*</include> </includes> </resource> </resources>
如图所示:
(5)controller层代码如下
jsp层
启动应用,成功访问