JSD-2204-同步和异步请求-Ajax-Day13

本文介绍了同步和异步请求的概念,强调了异步请求在页面局部刷新中的重要性。通过axios框架讲解了如何在客户端发起异步请求,并详细列举了GET和POST请求的应用场景。此外,文章还展示了如何使用Ajax实现登录、注册和商品添加功能,给出了相关控制器和实体类的目录结构。最后,提到了晚课内容,包括表设计面试题和对异步注册登录功能的复习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.同步请求和异步请求

  • 同步: 指单线程依次做几件事
  • 异步: 指多线程同时做几件事
  • 同步请求: 指客户端只有一个主线程,既要负责页面展示相关也要负责发请求获取数据, 由于只有一个线程当发出请求时则不再展示页面(清空页面) 当把数据请求回来之后再把请求到的数据显示到页面中, 这样的话就只能实现页面的整体改变
  • 异步请求: 指客户端由主线程负责显示页面, 由子线程负责发请求获取数据,获取到数据之后把数据展示到原页面当中,这个过程就称为页面的局部刷新,局部刷新的场景非常广泛,所以异步请求是必须掌握的技能

1.1客户端如何发出异步请求

  • 通过axios框架发出异步请求

1.2GET和POST

  • Get请求: 请求参数在请求地址的后面通过?分隔, 参数可见所以敏感信息不建议用Get请求, 参数长度受限只能传递几k的数据
  • 应用场景: 从服务器获取数据时使用Get请求,比如各种查询操作, 删除数据时一般也使用get
  • POST请求: 给服务器传递数据时使用Post请求,请求参数在请求体里面, 参数没有大小限制,
  • 应用场景: 请求参数包含敏感信息(密码) , 文件上传
  • 能使用Get请求尽量使用Get ,无法使用Get的才使用POST

2.使用Ajax实现之前的登录和注册和商品添加

2.1目录结构

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);
        User u = mapper.selectByUser(user.getUsername());
        if (u!=null){
            return 2;//表示用户名已存在
        }
        mapper.insert(user);
        return 1;//注册成功
    }

    @RequestMapping("/login")
    public int login(@RequestBody User user){
        System.out.println("user = " + user);
        User u = mapper.selectByUser(user.getUsername());
        if (u!=null){
            if (user.getPassword().equals(user.getPassword())){
                return 1;//代表登录成功
            }
            return 2;//密码错误
        }
        return 3;//用户名不存在
    }
}

2.1.5Emp.java(员工对象)

package cn.tedu.boot3.entity;

public class Emp {
    private String name;
    private Double salary;
    private String job;

    @Override
    public String toString() {
        return "Emp{" +
                "name='" + name + '\'' +
                ", salary=" + salary +
                ", job='" + job + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }
}

2.1.6Product.java(商品对象)

package cn.tedu.boot3.entity;

public class Product {
    private Integer id;
    private String title;
    private Double price;
    private Integer num;

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", price=" + price +
                ", num=" + num +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }
}

2.1.7User.java(用户对象)

package cn.tedu.boot3.entity;

public class User {
    private Integer id;
    private String username;
    private String password;
    private String nick;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", nick='" + nick + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getNick() {
        return nick;
    }

    public void setNick(String nick) {
        this.nick = nick;
    }
}

2.1.8ProductMapper.java

package cn.tedu.boot3.mapper;

import cn.tedu.boot3.entity.Product;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface ProductMapper {

    @Insert("insert into product values(null,#{title},#{price},#{num})")
    void insert(Product product);
}

2.1.9 UserMapper.java

package cn.tedu.boot3.mapper;

import cn.tedu.boot3.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserMapper {

    @Select("select * from user where username = #{username}")
    User selectByUser(String username);

    @Insert("insert into user values(null,#{username},#{password},#{nick})")
    void insert(User user);
}

2.1.10bmi.html(身体指数测量页面)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
 <div>
   <h1>身体质量指数测试</h1>
   <input type="text" v-model="height" placeholder="请输入身高(单位:米)">
   <input type="text" v-model="weight" placeholder="请输入体重(单位:公斤)">
   <input type="button" value="开始测试" @click="f()">
 </div>
 <script type="text/javascript" src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
 <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
 <script type="text/javascript">
  let v = new Vue({
      el:"body>div",
      data:{
        height:"",
        weight:"",
          info:""
      },
      methods: {
        f(){
          //发出异步的get请求
          axios.get("/bmi?h="+v.height+"&w="+v.weight).then(function (response) {
            alert(response.data);
          })
        }
      }
  })
</script>
</body>
</html>

2.1.11index.html(主页)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
  <h1>工程首页</h1>
    <a href="/bmi.html">BMI身体质量指数测试</a>
  <input type="button" value="发get请求" @click="f1()">
    <input type="text" v-model="emp.name" placeholder="姓名">
    <input type="text" v-model="emp.salary" placeholder="工资">
    <input type="text" v-model="emp.job" placeholder="工作">
  <input type="button" value="发post请求" @click="f2()">
    <h1>注册和登录(异步版本)</h1>
    <a href="/reg.html">注册</a>
    <a href="/login.html">登录</a>
  <h1>商品管理系统</h1>
  <a href="/insert.html">添加商品</a>
</div>
<script type="text/javascript" src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script type="text/javascript">
  let v = new Vue({
      el:"body>div",
      data:{
          emp:{
              name:"",salary:"",job:""
          }
      },
      methods:{
          f1(){
              //发出异步请求
              axios.get("/helloAxios?info=tom").then(function (response) {
                  //response.data 代表服务器响应的数据
                  alert(response.data);
              })
          },
          f2(){
              //发出post亲求并且吧和页面进行双向绑定的员工对象里面的数据提交
              axios.post("/helloPost",v.emp).then(function (response) {
                  alert(response.data);
              })
          }

      }
  })
</script>
</body>
</html>

2.1.12insert.html(商品添加页面)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
  <h1>添加商品页面</h1>
  <input type="text" v-model="product.title" placeholder="商品标题">
  <input type="text" v-model="product.price" placeholder="商品价格">
  <input type="text" v-model="product.num" placeholder="商品库存">
  <input type="button" value="添加" @click="insert()">
</div>
<script type="text/javascript" src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script type="text/javascript">
let v = new Vue({
	el:"body>div",
	data:{
	  product:{
	    title:"",
        price:"",
        num:""
      }
	},
    methods:{
	  insert(){
	    axios.post("/insert",v.product).then(function (response) {
          alert("添加完成!");
          location.href = "/";//返回首页
        })
      }
    }
})
</script>
</body>
</html>

2.1.13login.html(登录页面)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
  <h1>登录</h1>
  <input type="text" v-model="user.username" placeholder="请输入用户名">
  <input type="text" v-model="user.password" placeholder="请输入密码">
  <input type="button" value="登录" @click="login()">
</div>
<script type="text/javascript" src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script type="text/javascript">
let v = new Vue({
	el:"body>div",
	data:{
	  user:{
	    username:"",
        password:""
      }
	},
    methods:{
	  login(){
	    axios.post("/login",v.user).then(function (response) {
          if (response.data==1){
              alert("登陆成功");
              location.href = "/";
          }else if(response.data==2){
              alert("用户名不存在");
          }else{
              alert("密码错误");
          }
        })
      }
    }
})
</script>
</body>
</html>

2.1.14reg.html(注册页面)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <h1>注册页面</h1>
    <input type="text" v-model="user.username" placeholder="用户名">
    <input type="text" v-model="user.password" placeholder="密码">
    <input type="text" v-model="user.nick" placeholder="昵称">
    <input type="button" value="注册" @click="reg()">
</div>
<script type="text/javascript" src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script type="text/javascript">
    let v = new Vue({
        el: "body>div",
        data: {
            user: {
                username:"",
                password:"",
                nick:""
            }
        },
        methods: {
            reg() {
                //发出异步请求
                axios.post("/reg", v.user).then(function (response) {
                    if (response.data == 1){
                        alert("注册成功");
                        //修改浏览器的请求地址为首页
                        location.href = "/";
                    }else{
                        alert("用户名已存在");
                    }
                })
            }
        }
    })
</script>
</body>
</html>

2.1.15application.properties(配置文件)

spring.datasource.url=jdbc:mysql://localhost:3306/empdb?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false
spring.datasource.username=root
spring.datasource.password=root

3.晚课内容: 将下面面试题做完之后,将今天下午异步版本的注册登录功能反复写到熟练为止

3.1表设计面试题

2021年过年时小明在这些天都收到了许多亲戚\朋友还有同事的红包,也发出了一些红包,有的是微信,有的是支付宝也有现金,请参考下面的题目帮小明设计表格保存红包的信息

1.设计表 (至少包含一张流水表)

  • 列出需要保存的所有信息
  • 关系,红包类型,红包金额,时间,性别,名字
  • 人物表

        create table person(id int primary key auto_increment,name varchar(20),gender         varchar(5),rel varchar(20));

  • 流水表

        create table trade(id int primary key auto_increment,money int,time date,type         varchar(5),p_id int)charset=utf8;

  • 准备数据:

        人物表:

        insert into person values(null,'刘德华','男','亲戚'),(null,'杨幂','女','亲戚'),(null,'马云','男','同事'),(null,'特朗普','男','朋友'),(null,'貂蝉','女','朋友');

        流水表:

    刘德华 微信 收1000 2021-03-20

    杨幂 现金 收500 发50 2021-04-14

    马云 支付宝 收20000 发5 2021-03-11

    特朗普 微信 收2000  2021-05-18

    貂蝉 微信 发20000 2021-07-22

        insert into trade values(null,1000,'2021-03-20','微信',1),

        (null,500,'2021-04-14','现金',2),

        (null,-50,'2021-04-14','现金',2),

        (null,20000,'2021-03-11','支付宝',3),

        (null,2000,'2021-05-18','微信',4),

        (null,-20000,'2021-07-22','微信',5);

2.统计2021年2月15号到现在的所有红包收益

        select sum(money) from trade where time>"2021-2-15";

3. 查询2021年2月15号到现在 金额大于100 所有女性亲戚的名字和金额

        select name,money

        from person p join trade t on t.p_id=p.id

        where time>"2021-2-15" and money not between -100 and 100 and gender='女' and rel='亲戚';

4. 查询三个平台(微信,支付宝,现金)分别收入的红包金额

        select type,sum(money) from trade where money>0 group by type;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值