1、要求打包方式一定为war包
2、要求jsp页面放在webapp目录下, war才有, jar 没有
3、导入jsp相关的依赖
<!-- jsp相关的依赖: jstl, jsp, tomcat --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- tomcat的依赖: 包含servlet-api, 不要导入servlet-api, spring-boot-starter-tomcat包含Servlet-api --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <!-- jsp依赖: 类似之前: jsp-api --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency>
4、application.yml 配置JSP支持 (视图解析器中前缀,后缀)
spring:
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
注意:放在WEB-INF下资源, 浏览器不能直接访问, 通过Controller的转发方式访问, 重定向也不能访问
jsp页面:
<c:if test="${empty name }"> <a href="">登录</a> </c:if> <c:if test="${not empty name}"> <h1>欢迎:${name }</h1> </c:if>
controller页面:
@Controller public class IndexController { @GetMapping("/index") public String toIndex(Model model) { model.addAttribute("name", "zhansgan"); return "index"; }