Json
{“id”: “100”,“name”:“tomcat”,“age”:18,“sex”:“男”}
[1,2,3,4,“张三”,“李四”]
[1,2,true,false,{“id”:100,“name”:“tomcat”},[{arrays: [[],[],[]]},5,6]]、
MVC参数接收
RestFul结构(难点)
传统get请求业务说明
需求:向后端服务器传递多个参数,
需求说明: 向后端服务器传递多个参数, name=tomcat, age=18,sex=男
URL地址: http://localhost:8080/getUser?name=tomcat&age=18&sex=男
该方法能否优化? 能否降低字节数量?
RestFul参数拼接
语法: 省略key,将value使用/的方式进行分隔.并且位置固定.
URL地址: http://localhost:8080/getUser/tomcat/18/男
先修改URL地址
RestFul参数接收
优化:
如果restFul的属性名称与对象的属性名称一致,则可以利用对象接收
RestFul请求路径的通用写法
例子:
- http://localhost:8080/getUserById?id=100
- http://localhost:8080/deleteUserById?id=100
- http://localhost:8080/updateUserById?id=100&name=tomcat
- http://localhost:8080/insertUser POST 提交
问题: 上述的操作 意图特别的明显. 对后期操作会带来不安全的风险.
优化: restFul风格的请求名称的要求,不能出现动词
http://localhost:8080/userById?id=100 类型: GET 查询业务逻辑
http://localhost:8080/userById?id=100 类型: Delete 删除业务逻辑
http://localhost:8080/userById?id=100&name=tomcat 类型: PUT 更新业务逻辑
http://localhost:8080/user 类型: POST 新增业务逻辑
请求类型的种类
常用4种:get/post/put/delete
注解总结
-
@PathVariable restful结构,接收参数的注解
-
@GetMapping(“”) 只能接收get请求类型
-
@DeleteMapping(“”)
-
@PostMapping(“”)
-
@PutMapping(“”)
-
@RestController 标识controller类 返回值为Jason @Controller@ResponseBody结合体
-
@CrossOrigin //允许跨域访问
前后端调用
demo
</head>
<body>
<!-- 1导入js文件 -->
<script src="js/axios.js"></script>
<!-- 2编辑js代码 -->
<script>
// url地址:http://localhost:8080/findUser
let url1="http://localhost:8080/axios/findUser";
//(url地址,参数)
axios.get(url1) //发起ajax请求
.then(function(promise){ //成功之后执行回调函数,promise是返回值对象
console.log(promise.data) //输出
})
// axios.get(url1);
// .then(res=>{
// })
</script>
<h1>学习Axios的ajax调用</h1>
</body>
package com.jt.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
//@Controller
//@ResponseBody
@RestController //两个结合体
@CrossOrigin //允许跨域访问
@RequestMapping("/axios") //抽取公共部分
public class AxiosController {
@RequestMapping("/findUser")
public String findUser(){
return "查询用户成功";
}
}
前端网页:
axios用法
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lqty6RMK-1645446783559)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220221144822121.png)]
浏览器F12用法
Network,(console)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DyphHevS-1645446783560)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220221145444155.png)]
Axios-Get传参
参数拼接写法
多参数:axios.get(url2,{params:user1})
前端:
后端:
html结果:
network可以查看执行内容
restful传参
]
network可以查看执行内容
[外链图片转存中…(img-le7EbIZM-1645446783562)]
restful传参
[外链图片转存中…(img-7AGG65Cu-1645446783563)]
[外链图片转存中…(img-BUn7Wraz-1645446783563)]