1. SpringBoot集成JSP
1.1 配置所需依赖
pom依赖管理
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.guo.springboot</groupId>
<artifactId>springboot-jsp-010</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--SpringBoot框架Web项目起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--引用SpringBoot内嵌Tomcat对jsp的解析依赖,不添加解析不了jsp-->
<!--仅仅是展示jsp页面,只添加以下一个依赖-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
</dependencies>
<build>
<!--SpringBoot项目默认推荐使用的前端引擎是Thymeleaf
现在我们要使用SpringBoot集成jsp,手动指定jsp最后编译的路径
而且SpringBoot集成jsp编译jsp的路径是SpringBoot规定好的位置
META-INF/resources -->
<resources>
<resource>
<!--源文件夹-->
<directory>src/main/webapp</directory>
<!--指定编译到META-INF/resources-->
<targetPath>META-INF/resources</targetPath>
<!--指定源文件夹中的哪个资源要编译进去-->
<includes>
<include>*.*</include>
</includes>
</resource>
</resources>
<plugins>
<!--SpringBoot项目编译打包的插件-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
1.2 配置视图解析器
application.properties核心配置文件
#配置视图解析器 前缀后缀
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
1.3 代码测试
IndexController
package com.guo.springboot.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class IndexController {
@RequestMapping(value = "/say")
public @ResponseBody ModelAndView say(){
ModelAndView mv = new ModelAndView();
mv.addObject("message","hello,SpringBoot");
mv.setViewName("say"); //视图名称
return mv;
}
/*这种方法只是对ModelAndView的一种拆分(将Model和View拆分为两部分)*/
@RequestMapping(value = "index")
public String index(Model model){
model.addAttribute("message","HelloWord!");
return "say"; //响应的视图名称say
}
}
1.4 创建页面
JSP页面,显示响应的数据----say.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>${message}</h1>
</body>
</html>
1.5 测试结果