1.springBoot对JSP的支持
springBoot虽然支持JSP,但是官方不建议使用,下面是官方文档解释
When running a Spring Boot application that uses an embedded servlet container (and is packaged as an executable archive), there are some limitations in the JSP support.
With Jetty and Tomcat, it should work if you use war packaging. An executable war will work when launched with java -jar, and will also be deployable to any standard container. JSPs are not supported when using an executable jar.
Undertow does not support JSPs.
Creating a custom error.jsp page does not override the default view for error handling. Custom error pages should be used instead.
对应百度翻译:
当运行使用嵌入式servlet容器(并打包为可执行存档)的Spring Boot应用程序时,JSP支持存在一些限制。
有了Jetty和Tomcat,如果你使用战争包装,它应该可以工作。当使用java-jar启动时,一个可执行的war可以工作,并且可以部署到任何标准容器中。使用可执行jar时不支持JSP。
Undertow不支持JSP。
创建自定义错误。jsp页面不会覆盖错误处理的默认视图。应改用自定义错误页。
但是由于各种原因,我们在使用中还会使用springBoot+jsp的框架进行项目的开发,下面是搭建教程
2.搭建springBoot+JSP框架
1.使用IDEA搭建springBoot项目项目
因为idea对springBoot的有很好的支持,这里我就使用IDEA来进行教程的编写,还在用eclipse的童鞋,是时候学一下了(手动狗头)。
搭建如下图所示:
点击idea上的file->new->project
选择Spring Initializr(该方式是根据自己的需求通过网页创建一个压缩包下载到本地,简单快捷,也可以直接在浏览器输入https://start.spring.io/,进行项目的搭建,这种方式必须联网哦。)
选择完成后点击next
下面是选择一些需要的maven依赖(因为只是演示jsp项目的搭建这里我选择任何依赖)
项目名称和存放地址
搭建好的项目目录如图所示:
到此springboot的项目搭建完成,下面开始构建jsp页面。
2.springBoot项目集成jsp页面。
首先需要在maven的依赖文件pom.xml中加上对jsp支持的依赖(这里也需要联网才能下载依赖哦)
<!--用于编译jsp-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<!--支持jstl->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!--servlet开启-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
因为springBoot项目不存在webapp目录我们需要创建,创建结构如下
然后在idea中设置webapp路径
配置视图解析器,打开application.properties,配置视图
#项目名称
spring.application.name=springbootjsp
#项目访问名称,如果不配置直接访问bean就可以
#server.servlet.context-path=/springbootjsp
#端口
server.port=9090
#Spring boot视图配置
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
#静态文件访问配置
spring.mvc.static-path-pattern=/static/**
创建hello.jsp测试页面
代码
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: test
Date: 2022/2/7
Time: 20:47
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
hello!!!
</body>
</html>
创建编写测试类
代码:
package com.example.springbootjsp;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Controller
public class TestController {
@RequestMapping("test")
public String test(){
//对应的jsp页面,在jsp下对的路径以及页面名称
return "hello";
}
}
启动项目测试
在浏览器中输入http://127.0.0.1:9090/test,如下图所示
项目创建成功!
需要注意的是 WEB-INF是是受保护的目录,不能直接访问这个页面,需要通过后台才能访问,如果需要直接访问页面,需要把页面放在web-inf外边。
结束,感谢观看