- 在Spring Boot项目中是不推荐使用jsp作为视图层技术的
- 打jar包不能访问jsp资源,war包可以
添加依赖
以往的web项目是将项目部署的tomcat容器当中,tomcat负责将JSP编译成servlet并将其执行,而负责处理这个过程的句式jsp引擎。虽然SpringBoot中内嵌了一个tomcat容器,但是却没jsp引擎,所以SpringBoot内嵌的tomcat是不能处理jsp的。所以如果想在SpringBoot项目中使用jsp就必须要添加jsp引擎的相关依赖;
<!-- 解析jsp类库 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<build>
<!--
SpringBoot 要求 jsp 文件必须编译到指定的 META-INF/resources 目录下才能访问,否则访问不到
-->
<resources>
<resource>
<!--源文件位置-->
<directory>src/main/webapp</directory>
<!--指定编译到 META-INF/resources,该目录不能随便写-->
<targetPath>META-INF/resources</targetPath>
<!--指定要把哪些文件编译进去,**表示 webapp 目录及子目录,*.*表示所有文件-->
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
</build>
复制代码
添加好相关依赖后应该考虑jsp应该存放在什么样的目录下:jsp页面应该存放于“webapp”的目录下WEB-INF;webapp目录应该存放于main目录下,并与java,resources目录同一级别的位置
Idea 集成
-
选中项目–>File–>Project Structure–>Modules,选择对应的项目名,然后选择web,然后点击Web Resource Directories下的“+” 号,指定webapp为路径。
-
中途会提示是否生成文件夹,确认下就行了,最后会多个webapp文件夹,效果如下↓
-
指定SpringBoot的启动目录,添加上**
$ContentRoot$
** -
设置application.properties
#页面默认前缀目录 默认在webapp下有别的文件夹可以,以文件夹/往下加 spring.mvc.view.prefix=/ #页面默认后缀目录 spring.mvc.view.suffix=.jsp 复制代码
-
指定webapp为支持web技术的目录之后,该目录的图标会增加一个点,这个时候右键就有创建jsp页面的快捷方式了
-
测试是否可行
-
在webapp下创建demo.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> ${title} </body> </html> 复制代码
-
编写controller
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class ViewController { @GetMapping("demo") public String demo(Model model){ model.addAttribute("title","SpringBoot中集成使用jsp"); return "demo"; } } 复制代码
-
Eclipse 集成
使用Eclipse 集成JSP 相比idea 来说,就简单多了,接下来继续。
-
设置application.properties(或者是application.yml文件,配置方式不同而已)
#页面默认前缀目录 默认在webapp下有别的文件夹可以,以文件夹/往下加 spring.mvc.view.prefix=/ #页面默认后缀目录 spring.mvc.view.suffix=.jsp 复制代码
-
创建启动类
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class JspApplication { public static void main(String[] args) { SpringApplication.run(JspApplication.class,args); } } 复制代码
-
在webapp下创建demo.jsp(这里仅仅为了演示功能,在正式项目时,最好按照功能分别创建文件夹存储)
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> ${title} </body> </html> 复制代码
-
编写controller
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class ViewController { @GetMapping("demo") public String demo(Model model){ model.addAttribute("title","SpringBoot中集成使用jsp"); return "demo"; } } 复制代码
-
右击JspApplication.java,输入网址:http://localhost:8080/demo