一. HTTP協議
? ? ? ? 1. HTTP協議:Hyper Text Transfer Protocol,超文本傳輸協議,規定了瀏覽器和服務器之間數據傳輸的規則
? ? ? ? 2. HTTP協議特點:
? ? ? ? ? ? ? ? ① 基于TCP協議:面向鏈接,安全
? ? ? ? ? ? ? ? ② 基于請求-響應模型的:一次請求對應一次響應
? ? ? ? ? ? ? ? ③ HTTP協議是無狀態的協議:對于事物處理沒有記憶能力,每次請求-響應都是獨立的(缺點:多次請求間數據不能共享;優點:速度快)
二. HTTP-請求協議
? ? ? ? 1. 請求數據格式
? ? ? ? 請求方式-get:請求參數在請求行中,沒有請求體(如:localhost:8080/hello?name=卡莎);get請求大寫在瀏覽器中是有限制的。
? ? ? ? 請求方式-post:請求參數在請求體中;post請求大小是沒有限制的
? ? ? ? 2. 請求數據獲取
? ? ? ? ? ? ? ? (1) web服務器(Tomcat)對HTTP協議的請求數據進行解析,并進行了封裝(HttpServletRequest),在調用Controller方法的時候傳遞給了該方法。這樣,就使得程序員不必直接對協議進行操作,web開發更加便捷
package com.example;import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class RequestController {@RequestMapping("/request")public String request(HttpServletRequest request){//1.獲取請求方式System.out.println("獲取請求方式" + request.getMethod());//2.獲取URL地址System.out.println("獲取URL地址" +request.getRequestURL());System.out.println("獲取URI地址" +request.getRequestURI());//3.獲取請求協議System.out.println("獲取請求協議" +request.getProtocol());//4.獲取請求參數-name.ageSystem.out.println("獲取請求參數" +request.getParameter("name"));System.out.println("獲取請求參數" +request.getParameter("age"));//5.獲取請求頭-AcceptSystem.out.println("獲取請求頭Accept" +request.getHeader("Accept"));return "OK";}
}
三. HTTP-響應協議
? ? ? ? 1. 響應數據格式
? ? ? ? ?2. 響應數據設置
? ? ? ? ? ? ? ? 1. web服務器對HTTP協議的響應數據進行了封裝(HttpServletResponse),并在調用Controller方法的時候傳遞給了該方法。這樣就使得程序員不必直接對協議進行操作,讓Web開發更加便捷
package com.example;import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.io.IOException;@RestController
public class ResponseController {/** 方式一 原始HttpServletResponse* */@RequestMapping("/response")public void response(HttpServletResponse response) throws IOException {//1.設置響應狀態碼response.setStatus(HttpServletResponse.SC_OK);//2.設置響應頭response.setHeader("Content-Type","text/html");//3.設置響應體response.getWriter().write("<h1>Hello Response</h1>");}/** 方式二:spring 設置響應數據* */@RequestMapping("/response2")public ResponseEntity<String> responseEntity() {//鏈式編程return ResponseEntity.status(HttpServletResponse.SC_OK).header("Content-Type","text/html").body("<h1>Hello ResponseEntity</h1>");}
}
??
? ? ? ? 注意:響應狀態碼 和 響應頭如果沒有特殊要求的話,通常不手動設定。服務器會根據請求處理的邏輯,自動設置響應狀態碼和響應頭