椒江网站建设578做网站,企业网站seo工作,网站建设技术合伙人的技术股份,最好的网站设在SpringBoot应用开发中#xff0c;处理Http请求是一项基础且重要的任务。Spring Boot通过提供一系列丰富的注解极大地简化了这一过程#xff0c;使得定义请求处理器和路由变得更加直观与便捷。这些注解不仅帮助开发者清晰地定义不同类型的HTTP请求如何被处理#xff0c;同时…在SpringBoot应用开发中处理Http请求是一项基础且重要的任务。Spring Boot通过提供一系列丰富的注解极大地简化了这一过程使得定义请求处理器和路由变得更加直观与便捷。这些注解不仅帮助开发者清晰地定义不同类型的HTTP请求如何被处理同时也提升了代码的可读性和维护性。
一、RequestMapping
RequestMapping用于将特定的HTTP请求映射到特定的方法上。可用于类级别和方法级别上以下是代码示例。
RestController
RequestMapping(/customer-api/) // 类级别所有方法都以customer-api开头
public class CustomerApi{RequestMapping(value /get-customer-by-id, method RequestMethod.GET){ // 方法级别当收到对/customer-api/get-customer-by-id路径的GET请求时会调用getCustomerById方法。ResponseCustomer getCustomerById(RequestParam(id) Integer id)……}
}本节示例中RestController和RequestParam注解可以先忽略下面会介绍到。
二、PutMapping、DeleteMapping、GetMapping和PostMapping
为了更加明确表示不同的HTTP方法Spring Boot提供了一组特定的注解分别对应PUT, DELETE、GET、POST增删改查请求。
RestController
RequestMapping(/customer-api/)
public class CustomerApi{PutMapping(/add-customer) // 增加的请求,和RequestMapping的PUT方式等价Response? addCustomer(RequestBody Customer customer)……}DeleteMapping(/delete-customer-by-id) // 删除的请求,和RequestMapping的DELETE方式等价Response? deleteCustomer(RequestParam(id) Integer id)……}PostMapping(/update-customer) // 更新的请求,和RequestMapping的POST方式等价Response? updateCustomer(RequestBody Customer customer)……}// RequestMapping(value /get-customer-by-id, method RequestMethod.GET) // 方式1GetMapping(/get-customer-by-id) // 和方式1是等价的。ResponseCustomer getCustomerById(RequestParam(id) Integer id)……}
}三、RequestParam和PathVariable
RequestParam用于获取查询参数PathVariable用于获取路径变量
GetMapping(/get-customer-by-id){ ResponseCustomer getCustomerById(RequestParam(id) Integer id) // RequestParam就可获取请求路径/get-customer-by-id?id1中的id的值……}GetMapping(/get-customer/{id}){ ResponseCustomer getCustomerById(PathVariable(id) Integer id) // PathVariable可获取路径/get-customer/{id}中的id的值……}四、RequestBody
RequestBody注解用于将 HTTP 请求的主体内容绑定到方法的参数上。通常用于处理 POST 和 PUT 请求当请求的主体是 JSON 或 XML 格式的数据时非常有用。 示例见第二节这里就不重复赘述了。
五、RestController和Controller
RestController和Controller都是用于定义控制器类的注解但是两者之间有细微的差异。 RestController是一个组合注解相当于Controller和ResponseBody。 用RestController标注的API类其中的方法会直接返回数据如JSON、XML,不会返回视图。 Controller刚好相反它标注的类中的方法会直接返回视图如JSP、Thymeleaf模版等。
小结现在的微服务项目基本都是前后端分离所以Controller已经慢慢的淡出了视野很少使用而RestController已然成为了主流。
后面有时间了在聊聊GET和POST请求的区别大厂面试被问到的频次贼高。