在每個(gè)類之前申明@RestController注釋
@RestController 是@controller和@ResponseBody 的結(jié)合
@Controller 是將當(dāng)前修飾的類注入SpringBoot IOC容器,使得從該類所在的項(xiàng)目跑起來的過程中,這個(gè)類就被實(shí)例化
@ResponseBody 是指該類中所有的API接口返回的數(shù)據(jù)都會(huì)以JSON字符串的形式返回給客戶端
聲明API接口@RequestMapping注釋
@RequestMapping注解是一個(gè)用來處理請求的注解,可用于映射一個(gè)請求或一個(gè)方法,可以用在類或方法上(類上表示訪問每個(gè)方法鏈接前必須帶入類上的注釋名,如:http://localhost:8888/main/test)
@RestController
@RequestMapping("/main")
public class User {
@RequestMapping("/test")
public String hello() {
return "hello world!!";
}
}

訪問地址
一屬性定義:value定義訪問名稱、params定義請求參數(shù)中必須包含該屬性 、method定義類型默認(rèn)GET請求,支持多個(gè)類型使用對象通過逗號隔開,如:@RequestMapping(value ="/test", method = {RequestMethod.GET, RequestMethod.POST})。
二獲取傳參:在方法中定義傳參類型,即可獲取改傳參數(shù)據(jù),如:
public String hello(int id) {
return "hello world!!"+id;
}

訪問鏈接
三HttpServletRequest對象代表客戶端的請求,當(dāng)客戶端通過HTTP協(xié)議訪問服務(wù)器時(shí),HTTP請求頭中的所有信息都封裝在這個(gè)對象中,可以通過改對象獲取參數(shù)、請求頭信息等
四HttpServletResponse則是對服務(wù)器的響應(yīng)對象。這個(gè)對象中封裝了向客戶端發(fā)送數(shù)據(jù)、發(fā)送響應(yīng)頭,發(fā)送響應(yīng)狀態(tài)碼的方法
package com.example.demo;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.*;
@RestController
@RequestMapping(value = "/main")
public class User {
@RequestMapping(value ="/test",params = "id", method = {RequestMethod.GET, RequestMethod.POST})
public String hello(HttpServletRequest request, HttpServletResponse response) {
System.out.println(request);
System.out.println(response);
return "hello world!!";
}
}
擴(kuò)展注釋
@Autowired:類成員變量、方法及構(gòu)造函數(shù)進(jìn)行標(biāo)注,讓 spring 完成 bean 自動(dòng)裝配的工作
@GetMapping:處理get方式請求的映射
@PostMapping:處理post方式請求的映射
@PutMapping:處理put方式請求的映射
@DeleteMapping:處理delete方式請求的映射
@GetMapping就相當(dāng)于@RequestMapping(method=RequestMethod.GET),它會(huì)將get映射到特定的方法上