一、SpringBoot整合Web资源
1. 创建项目
1. 1 添加新依赖
<!--springBoot整合JSP添加依赖 -->
<!--servlet依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!--jstl依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!--使jsp页面生效 html jsp-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
1. 2 添加WEB资源页面
说明: 在springBoot项目的根目录中添加webapp文件目录.格式如下
- 修改打包方式
- 配置YML文件
server:
port: 8090
servlet:
#项目默认发布路径/根目录
context-path: /
#SpringBoot数据源配置
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/jtdb?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
username: root
password: root
#配置SpringMVC的视图解析器
mvc:
view:
prefix: /WEB-INF/ # /默认代表根目录 src/main/webapp
suffix: .jsp
#SpringBoot整合Mybatis-plus
mybatis-plus:
#定义别名包 作用: 以后封装POJO对象时自动进行拼接
type-aliases-package: com.jt.pojo
#引入mapper配置文件
mapper-locations: classpath:/mybatis/mappers/*.xml
#开启驼峰映射
configuration:
map-underscore-to-camel-case: true
#打印MybatisPlus执行sql日志
logging:
level:
com.jt.mapper: debug
- 业务需求说明
用户通过网址: http://localhost:8090/findAll 要求跳转到userList.jsp页面中 之后展现数据库user表所有记录.
- 修改工作目录
- 编辑 UserController
package com.jt.controller;
import com.jt.pojo.User;
import com.jt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
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.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
//@RestController //1.返回数据是JSON数据 2.表示Ajax请求的结束 3.返回值的是字符串本身
// 4.不会执行SpringMVC中的组件 视图解析器
@Controller //跳转到指定的页面中 会执行视图解析器 进行路径的拼接 前缀+后缀
public class UserController {
@Autowired
private UserService userService;
/**
* 请求用户请求: http://localhost:8090/findAll
* 参数: 暂时没有
* 返回值: 特定页面名称
* 前缀: /WEB-INF/
* 页面名称: userList
* 后缀: .jsp
*/
//方式: 页面同步请求的方法
@RequestMapping("/findAll")
public String findAll(Model model){
List<User> userList = userService.findAll();
//目的:需要通过request对象将数据带到页面中进行展现
model.addAttribute("userList",userList);
//springMVC中采用视图解析器的形式 添加 前缀+后缀
return "userList"; //返回页面逻辑名称
}
}
- 页面效果展示
- 知识盲区
WEB-INF 是什么? 保护页面资源 所有的请求都必须经过Controller中转,用户不能直接跳转页面。
2. 关于Ajax说明
问题: 为什么Ajax可以实现异步调用呢???
同步 异步加载机制区别
核心部件:Ajax引擎