一、后端项目搭建

1、创建项目

项目名称: springboot_demo5_axios
要求:mapper、service、pojo、controller
在这里插入图片描述

2 SpringMVC 参数传递方式

2.1)简单的参数传递

url地址:http://localhost:8090/getUserById?id=100
编辑后台Controller代码:

/**
     * URL: http://localhost:8090/getUserById?id=100
     */
    @RequestMapping("/getUserById")
    public String getUserById(Integer id){

        return "动态的获取参数:"+id;
    }
2.2)对象的方式传递

URL:http://localhost:8090/getUser?id=100&name=“tomcat”&age=18
后台代码说明:

/**
     * 接收对象的参数:
     * URL: http://localhost:8090/getUser?id=100&name="tomcat"&age=18
     * 对象解析为JSON数据.
     */
    @RequestMapping("/getUser")
    public User getUserById(User user){

        return user;
    }
2.3)RestFul风格

特点:

  1. 参数需要使用/ 进行分割
  2. 参数的位置是固定的.
  3. restFul请求方法路径不能出现动词

作用:
用户可以通过一个URL请求的地址,可以实现不同的业务操作
知识回顾:
查询: http://localhost:8090/getUserById?id=100 类型:get
新增: http://localhost:8090/insertUser 类型:post
更新: http://localhost:8090/updateUser 类型:post
删除: http://localhost:8090/deleteUserById?id=200 类型:get
意图明显: 常规的请求的方式其中包含了动词,导致操作的意图非常明显.

RestFul风格实现CURD操作:
1.查询: http://localhost:8090/user/100 type:GET
2.新增: http://localhost:8090/user/tomcat/18/男 type:POST
3.删除: http://localhost:8090/user/100 type:DELETE
4.更新: http://localhost:8090/user/mysql/100 type:PUT

2.4) RestFul风格-简单参数接收

入门案例

 /**
     * 1.restFul实现用户查询
     * URL: http://localhost:8090/user/100
     * type: GET
     * RequestMapping 默认的可以接收所有的请求类型
     * RestFul语法:
     *      1.参数的位置固定.
     *      2.参数必须使用{}包裹
     *      3.必须使用@PathVariable 动态的接收参数
     *      注意事项: {参数名称}必须与方法中的名称一致.
     */
    //@RequestMapping(value = "/user", method = RequestMethod.GET)
    @GetMapping("/user/{id}")
    public String restFulGet(@PathVariable Integer id){

        return "restFul动态的获取参数:"+id;
    }
2.5)RestFul风格-对象参数接收

入门案例:

/**
     * 需求: 查询name=tomcat age=18 sex=女的用户
     * 要求使用:restFul
     * URL: http://localhost:8090/user/tomcat/18/女
     * restFul的优化:
     *  如果{参数名称}与对象中的属性名称一致,
     *      则SpringMVC动态的为对象赋值,
     *      @PathVariable 可以省略
     * 注意事项:
     *      前后端的参数的传递必须保持一致!!!!
     */
    @GetMapping("/user/{name}/{age}/{sex}")
    public User restGetUser(User user){
        //执行后续的业务操作 userService
        return user;
    }

二、Axios学习

1、Axios介绍

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
特点:
1.从浏览器中创建 XMLHttpRequests
2.从 node.js 创建 http 请求
3.支持 Promise API
4.拦截请求和响应
5.转换请求数据和响应数据
6.取消请求
7.自动转换 JSON 数据
8.客户端支持防御 XSRF

结构说明:
	1. JS中原生提供了Ajax操作.  弊端: 操作特别的复杂 易用性较差.
	2. jQuery中的Ajax    封装了原生的JS Ajax    提高了开发的效率  
	3. Axios是VUE中默认支持的Ajax的请求的方式. 

== 特点:调用简洁,解决了 “回调地狱问题”!!!==

2、回调地狱问题(了解)

说明: 前端中如果需要发起大量的Ajax请求,并且Ajax请求有嵌套的关系,则可能引发回调地狱问题.
例子: 请求 参数A --1–结果B/参数B—2–结果C/参数C—3— 结果D
课下了解: 什么是回调地狱!!!
在这里插入图片描述

3、Axios 入门案例

3.1)编辑后台代码

编辑后台代码完成业务获取

 /** 快速完成
     * 查询用户信息
     * URL: http://localhost:8090/axios/getUser
     */
    @GetMapping("/axios/getUser")
    public String getUser(){
        return "你好Ajax入门";
    }
3.2)Axios调用步骤
  1. 导入Axios的JS文件
  2. 发起Ajax请求
  3. 解析返回值
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Axios</title>
	</head>
	<body>
		<h1>Axios练习</h1>
		<!-- 引入JS文件 -->
		<script src="../js/axios.js"></script>
		<script>
			/**
			 * 注意事项:
			 * 		1.Axios将原来的嵌套的结构,改为链式加载方式
			 *    2.回调函数中的data,不是服务器的返回值,是promise对象
			 * 
			 * 发起Ajax请求:
			 * 	1. GET请求获取数据
			 */
			axios.get("http://localhost:8090/axios/getUser")
					 .then(function(result){//promise对象
						//获取服务器返回值  promise.data
						 console.log(result.data)
					 })
			
		</script>
	</body>
</html>

result是promise对象,其中data表示服务器的返回值
在这里插入图片描述

4、Axios-Get-简单参数

4.1)前端Ajax请求
/**
			 *  GET请求-简单参数的写法
			 * 需求: 根据ID查询数据
			 * URL: http://localhost:8090/axios/getUserById?id=100
			 * then(): 回调函数通过then返回 结构
			 */
			axios.get("http://localhost:8090/axios/getUserById?id=100")
					 .then(function(result){
						 console.log(result.data)
					 })

4.2)后端Controller
 /**
     * 查询用户信息
     * URL: http://localhost:8090/axios/getUserById?id=100
     * 参数: id=100
     * 返回值: String
     */
    @GetMapping("/axios/getUserById")
    public String getUserById(Integer id){

        return "axios的ID查询:"+id;
    }

5、Axios-Get-resultFul结构

5.1)前端Ajax请求

在这里插入图片描述

	/**
			 * restFul风格实现业务传参 
			 * 需求: 根据name/age查询数据
			 * URL: http://localhost:8090/axios/user/tomcat/18
			 * 注意: 模版字符串优化参数  ``
			 */
			let name = "mysql"
			let age = 20
			axios.get(`http://localhost:8090/axios/user/${name}/${age}`)
					 .then(function(result){
						 console.log(result.data)
					 })

restFul风格实现业务,
传参注意:
传属性时,模版字符串优化参数需要用反撇号引起来
在这里插入图片描述

5.2)编辑后端Controller
/**
     * restFul ajax传参
     * URL: http://localhost:8090/axios/user/mysql/20
     * 参数: name/age
     * 返回值: User对象
     */
    @GetMapping("/axios/user/{name}/{age}")
    public User getUser2(User user){
        return user;
    }

6、Axios-Get-对象传参(重要!!!)

6.1 )F12的说明

一般用来检查网络的请求。使用network。其中不要添加缓存, 检查所有的请求的路径
在这里插入图片描述

6.2)需求说明

说明:如果用户查询数据,其中包含了多个参数,可以使用restFul风格(少量参数)/可以使用对象封装(多个参数)
如果参数较多则建议使用对象的方式封装.
案例:查询name=“mysql” age=18 sex="女"的用户,要求使用对象的方式封装参数

编辑前端Ajax
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Axios</title>
	</head>
	<body>
		<h1>Axios练习</h1>
		<!-- 引入JS文件 -->
		<script src="../js/axios.js"></script>
		<script>
				
				/**
				 * 需求: 实现对象方式的数据传递
				 * url:  http://localhost:8090/axios/user/getUserObj
				 * 语法: axios.get("url","参数").then(回调函数)
				 * 业务需求:  查询name="mysql" age=18   sex="女"的用户
				 */
				
				//封装对象
				let user = {
					name: "mysql",
					age: 18,
					sex: "女"
				}
			
				axios.get(
					"http://localhost:8090/axios/user/getUserObj",{params: user})
					.then(function(result){
						console.log(result.data)
					})
			
			/* 	axios.get("http://localhost:8090/axios/user/getUserObj",
				{
					//key: value  key固定写法 params 参数对象
					params: {
						//再写用户的参数
						name: "mysql",
						age: 18,
						sex: "女"
					}
				}).then(function(result){
					console.log(result.data)
				}) */
				
				
				
		</script>
	</body>
</html>

编辑后端Controller
 /**
     * restFul ajax传参
     * "http://localhost:8090/axios/user/getUserObj",{params:user} //前端传输对象
     * URL: http://localhost:8090/axios/user/mysql/20
     * 参数: name/age/sex
     * 返回值: User对象
     */
    @GetMapping("/axios/user/getUserObj")
    public User getUser3(User user){
        return user;
    }

7、Axios-Delete请求

7.1)Delete请求说明

一般用户通过Delete请求做删除操作. 删除的语法与Get请求的语法一致的.

7.2)Delete请求方式说明 了解delete代码结构
1.不带参数的删除
axios.delete(“url地址”).then(function(result){ … })
2.携带个别参数 ?id=100
axios.delete(“url地址?id=100”).then(function(result){ … })
3.restFul结构
可以使用模版字符串的方式简化代码结构(用反撇号包裹``,参数用花括号包裹{})
axios.delete( `url地址/xxx/xxx/xxx/{}/{}`).then(function(result){ … })
4.采用对象的方式进行参数传递
let 对象 = {xxxx:xxxx,xxxx:xxxx}
axios.delete( "url地址/xxx/xxx/xxx", {params: 封装后的对象}).then(function(result){ … })

8、Axios-post请求

8.1)编辑页面Ajax
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Axios-POST请求</title>
	</head>
	<body>
		<h1>Axios练习</h1>
		<!-- 引入JS文件 -->
		<script src="../js/axios.js"></script>
		<script>
					
					/* 
						1.什么时候使用post请求????
						  答:一般采用form表单提交时,采用post请求类型
								 主要用于数据的新增操作
								 
						2.get请求/post请求主要的区别
							get: 参数动态的拼接到URL地址中 ?id=xx&name=xxx 数据是可见的
							post: 一般采用post请求数据是涉密的 
					 */
					
					
					/**
					 * post业务:
					 * 		实现用户的新增 传递User对象
					 * 
					 * URL地址:
					 * 		http://localhost:8090/axios/insertUser
					 * 总结: 如果需要对象传参  
					 * 				1.get请求采用 axios.get(url,{params: 对象})
					 * 				2.post请求 axios.post(url,对象)
					 */
					let user = {
						name: "post请求的语法",
						age: 20,
						sex: '女'
					}
					let url1 = "http://localhost:8090/axios/insertUser"
					axios.post(url1, user)
							 .then(function(result){
								 console.log(result.data)
							 })				
		</script>
	</body>
</html>

8.2)参数的数据结构

说明:如果采用post的方式传递对象,则数据结构是一个JSON

在这里插入图片描述

8.3)编辑后端Controller
 /**
     *  需求:post请求实现数据入库
     *  URL: http://localhost:8090/axios/insertUser
     *  参数: "user对象结构"
     *  返回值: User对象返回
     *  注意事项:
     *      如果前端发起post请求方式,则传递的数据是一个JSON串
     *      常规参数: id=100 name="tomcat"
     *      post参数: {id:100,name:"tomcat"}
     *  解决方案:
     *       1.对象转化为JSON     @ResponseBody
     *       2.JSON串转化为对象   @RequestBody
     */
    @PostMapping("/axios/insertUser")
    public User insertUser(@RequestBody User user){
        return user;
    }

9、关于前后端调用细节说明

9.1)请求类型

在这里插入图片描述
请求的类型是由程序员手动控制
分类A
1.get 请求类型 查询
2.delete 请求类型 删除
分类B
1.post 请求类型 form表单提交 新增操作
2.put 请求类型 更新操作

9.2)关于POST请求说明

浏览器解析数据结构:
在这里插入图片描述
说明:数据在进行参数传递时,数据需要转化
在这里插入图片描述

10、Axios-post-restFul结构

10.1)编辑前端JS
	/**
					 * post请求 restFul的写法
					 * 实现用户新增入库
					 * url: http://localhost:8090/axios/user/name/age/sex
					 */
					let url2 = "http://localhost:8090/axios/user/redis/18/男"
					axios.post(url2)
							 .then(function(result){
								 console.log(result.data)
							 })

10.2)编辑后端Controller
/**
     * url:http://localhost:8090/axios/user/name/age/sex
     * 参数: 对象接收
     * 返回值: User对象  demo练习简单 由业务决定
     */
    @PostMapping("/axios/user/{name}/{age}/{sex}")
    public User insertUserRest(User user){
        System.out.println("调用service完成入库");
        return user;
    }

11、async-await用法-箭头函数(变态!!!)

11.1)概念解释

1.async/await 是ES7引入的新语法 可以更加方便的进行异步操作
2.async 关键字用在函数上. 返回值是一个promise对象
3.await 关键字用在async 函数中

11.2)箭头函数
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>async-await语法</title>
	</head>
	<body>
		<h1>Axios练习</h1>
		<!-- 引入JS文件 -->
		<script src="../js/axios.js"></script>
		<script>
					
					/**
					 * axios的get请求语法
					 * 知识点:
					 * 		1.箭头函数 主要简化回调函数的写法
					 * 			result =>替换function(result)
					 * 				
					 * 		思路: 重复的 固定的可以简化
					 * 		规则: 如果参数只有一个则括号可以省略
					 */
					let url = "http://localhost:8090/axios/getUserById?id=100"
					axios.get(url)
							 .then( result => {
								 alert(result.data)
							 })
					
		</script>
	</body>
</html>
11.3)async-await 操作
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>async-await语法</title>
	</head>
	<body>
		<h1>Axios练习</h1>
		<!-- 引入JS文件 -->
		<script src="../js/axios.js"></script>
		<script>
					
					/**
					 * axios的get请求语法
					 * 知识点:
					 * 		1.箭头函数 主要简化回调函数的写法
					 * 				result =>替换function(result)
					 * 		思路: 重复的 固定的可以简化
					 * 		规则: 如果参数只有一个则括号可以省略
					 *  	
					 * 		2.async-await简化  解构赋值
					 * 		2.1 async 需要标识函数
					 * 		2.2 await 需要标识ajax请求
					 *    上述的操作可以将多行js 封装为一行执行 简化代码操作
					 */
					
					//1.定义一个方法
					async function getUserById(){
							let url = "http://localhost:8090/axios/getUserById?id=100"
							//2.发起ajax请求  获取promise对象
							//let promise = await axios.get(url)
							//console.log(promise)
							//console.log(promise.data)
							
							//解构赋值 提取对象中有价值的数据
							let {data: resultData,status: code} = await axios.get(url)
							console.log(resultData)
							console.log(code)
					}
					
					//2.调用方法
					getUserById()
		</script>
	</body>
</html>

11.4)Axios配置信息

说明:可以通过下列的配置简化 Ajax请求的路径(默认基本请求路径)

//配置默认基本请求路径
	axios.defaults.baseURL = "http://localhost:8080/"

在这里插入图片描述

三、关于Axios练习

1、VUE+Axios 需求分析

说明:

  1. 利用VUE.js构建页面
  2. 利用Axios实现userList数据的获取, 利用VUE.js展现列表信息
  3. 完成页面数据的删除操作
  4. 完成页面数据的修改操作

2、绘制前端页面

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>VUE-Axios练习</title>
	</head>
	<body>
		<!-- 定义VUE根标签 -->
		<div id="app">
				<div align="center">
						<h1 align="center">用户新增</h1>
						名称: <input type="text" v-model.trim="addUser.name"/>
						年龄: <input type="text" v-model.number="addUser.age"/>
						性别: <input type="text" v-model.trim="addUser.sex"/>
						<button @click="addUserMe">新增</button>
				</div>
				<hr />
				<table id="tab1" border="1px" align="center" width="80%">
					<tr>
						<td colspan="5" align="center"><h1>用户列表</h1></td>
					</tr>
					<tr align="center">
						<td>编号</td>
						<td>姓名</td>
						<td>年龄</td>
						<td>性别</td>
						<td>操作</td>
					</tr>
					<!-- 指令: 可以循环数据+标签  v-for -->
					<tr align="center" v-for="user in userList">
						<td v-text="user.id"></td>
						<td v-text="user.name"></td>
						<td v-text="user.age"></td>
						<td v-text="user.sex"></td>
						<td>
							<button>修改</button>
							<button>删除</button>
						</td>
					</tr>
				</table>
		</div>
			
		<!-- 1.引入VUE.js -->
		<script src="../js/vue.js"></script>
		<!-- 2.引入Axios.js -->
		<script src="../js/axios.js"></script>
		
		<!-- 
				需求分析1:
					1.当用户打开页面时就应该发起Ajax请求获取userList数据.
					2.将userList数据 在页面中展现  
							2.1页面中的数据必须在data中定义
							2.2 ajax请求的结果赋值给data属性
					3.利用v-for指令实现数据遍历
					
				需求分析2:  用户数据入库操作
					1.在页面中准备用户新增文本框/按钮
					2.准备双向数据绑定的规则
					3.为按钮添加事件,实现数据新增入库.
							
		 -->
		<script>
				//设定axios请求前缀
				axios.defaults.baseURL = "http://localhost:8090"
				const app = new Vue({
					el: "#app",
					data: {
						//1.定义集合数据 null
						userList: [],
						//2.定义addUser对象  新增的用户数据
						addUser: {
							name: '',
							age: 0,
							sex: ''
						}
					},
					methods: {
						//1.定义getuserList方法 获取后台服务器数据
						async getUserList(){
							let{data: result} = await axios.get("/vue/getUserList")
							//ajax调用之后,将数据给属性.
							this.userList = result
						},
						//新增操作 请求类型: post  接收时需要使用json方式处理
						async addUserMe(){
								//不需要返回值
								await axios.post("/vue/insertUser",this.addUser)
								//将列表页面重新刷新
								this.getUserList()
						}
					},
					//调用生命周期函数
					mounted(){
						//console.log("vue对象实例化成功!!!!")
						//初始化时调用getUserList()
						this.getUserList()
					}
				})
		</script>
	</body>
</html>

3、 实现UserList查询

3.1)编辑UserController
@RestController
@CrossOrigin
@RequestMapping("/vue") //包含全部类型
public class VueController {

    @Autowired
    private UserService userService;

    /**
     *  需求: 查询用户表的所有数据
     *  url: /vue/getUserList
     *  参数: 不要参数
     *  返回值: List集合
     */
    @GetMapping("/getUserList")
    private List<User> getUserList(){

        return userService.getUserList();
    }

}

3.2)编辑UserService
@Service
public class UserServiceImpl  implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> getUserList() {

        //利用MP获取数据库记录
        //selectList(查询条件--用条件构造器来写)
        return userMapper.selectList(null);//
    }
}

4、实现用户入库操作

4.1)编辑UserController
/**
     * 实现用户数据新增
     * 网址: /vue/insertUser
     * 参数: 传递的是一个对象的JSON串
     * 类型: post请求类型
     * 返回值: void
     */
    @PostMapping("/insertUser")
    public void insertUser(@RequestBody User user){

        userService.insertUser(user);
    }
4.2)编辑UserService
  //利用MP添加数据库记录
    @Override
    public void insertUser(User user) {
        userMapper.insert(user);
    }
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐