1.同步请求和异步请求
- 同步: 指单线程依次做几件事
- 异步: 指多线程同时做几件事
- 同步请求: 指客户端只有一个主线程,既要负责页面展示相关也要负责发请求获取数据, 由于只有一个线程当发出请求时则不再展示页面(清空页面) 当把数据请求回来之后再把请求到的数据显示到页面中, 这样的话就只能实现页面的整体改变
- 异步请求: 指客户端由主线程负责显示页面, 由子线程负责发请求获取数据,获取到数据之后把数据展示到原页面当中,这个过程就称为页面的局部刷新,局部刷新的场景非常广泛,所以异步请求是必须掌握的技能
1.1客户端如何发出异步请求
1.2GET和POST
- Get请求: 请求参数在请求地址的后面通过?分隔, 参数可见所以敏感信息不建议用Get请求, 参数长度受限只能传递几k的数据
- 应用场景: 从服务器获取数据时使用Get请求,比如各种查询操作, 删除数据时一般也使用get
- POST请求: 给服务器传递数据时使用Post请求,请求参数在请求体里面, 参数没有大小限制,
- 应用场景: 请求参数包含敏感信息(密码) , 文件上传
- 能使用Get请求尽量使用Get ,无法使用Get的才使用POST
2.使用Ajax实现之前的登录和注册和商品添加
2.1目录结构
![](https://i-blog.csdnimg.cn/blog_migrate/84b3ad0c347f6dfaac84755ec7a5ce21.png)
2.1.1BMIController.java(体质检测)
package cn.tedu.boot3.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class BMIController {
@RequestMapping("/bmi")
public String bmi(float h,float w){
System.out.println("h = " + h + ", w = " + w);
//bmi = 体重/身高*身高
float bmi = w/(h*h);
if (bmi<18.5){
return "兄弟你瘦了!";
}
if(bmi<24){
return "体重正常!";
}
if (bmi<28){
return "微微胖!";
}
return "该运动起来了!";
}
}
2.1.2HelloController.java(测试ajax的)
package cn.tedu.boot3.controller;
import cn.tedu.boot3.entity.Emp;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/helloAxios")
public String helloAxios(String info){
return "测试成功"+info;
}
//如果客户端传毒的参数是以js中自定义对象的形式 则需要使用@RequestBody注解
@RequestMapping("helloPost")
public String helloPost(@RequestBody Emp emp){
System.out.println("emp = " + emp);
return "post测试成功!";
}
}
2.1.3ProductController.java(商品控制层)
package cn.tedu.boot3.controller;
import cn.tedu.boot3.entity.Product;
import cn.tedu.boot3.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProductController {
@Autowired
ProductMapper mapper;
@RequestMapping("/insert")
public void insert(@RequestBody Product product){
System.out.println("product = " + product);
mapper.insert(product);
}
}
2.1.4UserController.java(用户控制层)
package cn.tedu.boot3.controller;
import cn.tedu.boot3.entity.User;
import cn.tedu.boot3.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
UserMapper mapper;
@RequestMapping("/reg")
public int reg(@RequestBody User user){
System.out.println("user = " + user);