Read JavaWeb in one article, the front-end and back-end data interaction turns out to be like this

1. HTTP is the carrier of front-end and back-end data interaction

The request body of Request is loaded with the requested data sent by the front end to the back end; the
response body of Response is loaded with the data returned by the back end to the front end;

Of course, the URL in the request line of the Request can also carry the requested data sent by the front end to the back end, which will be described in detail later.

1. HTTP Request

Request模型
insert image description here

Request实例
insert image description here

2. HTTP Response

Repsonse模型
insert image description here
Response实例
insert image description here

2. Data interaction format JSON

1. JSON object and JSON string

  • A JSON string is a string that conforms to the JSON syntax
  • Each language has its own JSON syntax, so each language has its own form of JSON strings and JSON objects conforming to its own form.

2. Exchange JSON objects and JSON strings in different languages

JavaScript

// json字符串转json对象,调用parse方法:
//符合JSON语法的对象,所以是JSON字符串
var person='{"name":"zhangsan","sex":"男","age":"24"}';
var personObject = JSON.parse(person);
alert(personObject.name);//zhangsan

// json对象转为json字符串,调用stringify方法:
//符合JSON语法的对象,所以是JSON对象
var person={
    
    "name":"zhangsan","sex":"男","age":"24"};
var personString = JSON.stringify(person);
alert(personString);

Java

// json对象转json字符串,以JSONObject为中介
Student stu=new Student();
stu.setName("JSON");
stu.setAge("23");
stu.setAddress("北京市西城区");
JSONObject json = JSONObject.fromObject(stu);
String strJson=json.toString();
System.out.println("strJson:"+strJson); // trJson:{"address":"北京市西城区","age":"23","name":"JSON"}


// json字符串转json对象
String objectStr="{\"name\":\"JSON\",\"age\":\"24\",\"address\":\"北京市西城区\"}";
JSONObject jsonObject=JSONObject.fromObject(objectStr);
Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);
System.out.println("stu:"+stu); //stu:Student [name=JSON, age=24, address=北京市西城区]

3. How the front end sends data

1. Form sending data

Use the form form to transfer: there is an action attribute in the form form, you can use the action to submit data to the backend, and the action is followed by the url for background processing

<form action="${pageContext.request.contextPath}/login.action" method="post">
   用户名<input type="text" name="username"><br>
   密码<input type="password" name="password"><br>
</form>

2. JSON object to send data

  <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
  <script>
  <!--Json对象-->
    var user = {
    
    
      "username": "hahah",
      "password": "123456"
    };

    $.ajax({
    
    
      url:"/testJson",
      type: "GET",
      async: true,
      data: user,//Json对象
      dataType: 'json',
      success: function (data) {
    
    

      }
    });
  </script>

3. JSON string method

<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>

  <script>
    var user = {
    
    
      "username": "hahah",
      "password": "123456"
    };

    $.ajax({
    
    
      url:"/testJson3",
      type: "POST",
      async: true,
      contentType: "application/json;charset=UTF-8", //使用 application/json;charset=UTF-8
      data: JSON.stringify(user), //将JSON对象转换为JSON字符串
      dataType: 'json',
      success: function (data) {
    
    

      }
    });
  </script>

4. How the front end receives data

Write Ajax code to access the backend interface

$.ajax({
    
    
        url:'/heap',	//这是后端接口的url
        method:'get',
        success:function (res) {
    
    
            //res便是的数据便是后端拿到的数据
            //这里需要注意:res为局部变量,
            //所以需要在方法外定义一个变量把res赋值给他,才能在方法之外使用。
        },
    })

At this time, res is a JSON object. This is because: @ResponseBody annotation is mainly used to return json data to the front end. If you are lazy and just want to return an object, then adding @ResponseBody can automatically convert the returned object to json Pass it back to the front end.

But doesn't it mean that json has two formats...a json object and a json string. How do you prove that what you get is a json object instead of a json string. You only need to modify one place in the front-end code to prove
insert image description here
that if it is an object, then there are attributes, and I will print this attribute. If there is data, it can be explained that it is a json object
insert image description here

5. How does the backend request data

1. get request and post request

- get请求不存在请求实体部分,键值对参数放置在 URL 尾部;
- get请求存在请求实体部分,键值对参数放置在 请求的请求体;

- get和post相比,要快,是因为get和post的请求过程不同,不多前三步都是一样的,都是要先经过和服务器的三次握手:
1.浏览器请求tcp连接(第一次握手)
2.服务器答应进行tcp连接(第二次握手)
3.浏览器确认,并发送get请求头和数据(第三次握手,这个报文比较小,所以http会在此时进行第一次数据发送)
  get请求在第四步就会接收到了服务器返回的数据,而post请求在第四步是接收到服务器发送的100 continue指令,客户端在发送数据请求服务端,服务端才会去返回数据,
  就是说POST比GET多进行了一次客户端和服务器的打交道,GET请求产生了一个TCP数据包,而POST请求产生了两个TCP数据包

2. @RequestParam

@RequestParam绑定参数机制
- 如果不写@RequestParam(xxx)的话,那么会自动匹配方法参数,如果命名不同会默认接收为空。

@RequestParam有三个配置参数:
- required 是否必须传递参数,默认为 true,必须。
- defaultValue 可设置请求参数的默认值。
- value 为接收url的参数名(相当于key值)。

表单格式 +GET
If the http request is GET, the form parameters will be placed in the query parameters of the URL, for example:

// http://localhost:port/form?phone=roger&password=123456

@RequestMapping("form")
@ResponseBody
public User form(@RequestParam("phone")String phone,@RequestParam("password")String password){
    
    
    return new User(phone,password);
}

表单格式+POST
If the request method is POST, the form data is stored in the request body. You can add @RequestParam to the Controller method parameter to bind the data to the parameter.

// http://localhost:port/form

@RequestMapping("form")
@ResponseBody
public User form(@RequestParam("phone")String phone,@RequestParam("password")String password){
    
    
    return new User(phone,password);
}

3. @RequestBody

表单格式+POST

// http://localhost:port/form1

@RequestMapping("form1")
@ResponseBody
public User form1(@RequestBody MultiValueMap<String,String> user){
    
    
    String phone = user.getFirst("phone");
    String password = user.getFirst("password");
    return new User(phone,password);
}

JSON格式+POST
The key value of the json statement in the body should correspond to the attribute of the backend entity class one by one.

@Controller
@RequestMapping(value = "saveUser", method=RequestMethod.POST ) 
@ResponseBody  
public void saveUser(@RequestBody User user) {
    
     
    userService.batchSave(user); 
} 

6. How does the backend return data

The @ResponseBody annotation is mainly used to return json data to the front end. If you are lazy and just want to return an object, then add @ResponseBody to automatically convert the returned object into json and send it back to the front end.

Guess you like

Origin blog.csdn.net/m0_46638350/article/details/130236279