在 spring boot 中定义 get 请求,需要在 controller 类的方法上使用 @getmapping 注解(或 @requestmapping(method = requestmethod.get)),并指定 url 路径。该方法通常返回数据模型对象或包装后的响应体,spring mvc 会自动将其序列化为 json 格式并通过 http 200 状态码返回给客户端。

如何接收前端传递的查询参数?
使用 @RequestParam 注解可以接收 URL 查询字符串中的键值对参数。若参数非必填,需设置 required = false 并提供默认值,否则未传参时会抛出异常。对于复杂对象,可使用 @ModelAttribute 自动绑定。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.stereotype.Controller;
@Controller
public class QueryController {
@GetMapping("/search")
public String search(@RequestParam(required = false, defaultValue = "1") int page,
@RequestParam String keyword) {
return "results";
}
}
如何接收路径变量 Path Variable?
当参数是 URL 路径的一部分时,使用 @PathVariable 注解。它通过占位符(如 {id})与路径匹配,常用于获取资源 ID。与 @RequestParam 不同,路径变量是 URI 模板的一部分,不可省略。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.stereotype.Controller;
@Controller
public class PathController {
@GetMapping("/users/{id}")
public String getUser(@PathVariable Long id) {
return "user_detail";
}
}
GET 请求返回空值时的处理逻辑是什么?
当查询条件无匹配数据时,REST 接口应返回空集合 [] 而非 null,以避免前端解析错误。若使用 @RestController,直接返回实体类即可;若需统一包装,可返回自定义的 Result<t></t> 对象,其中 data 字段为空列表。


















