Spring Boot 控制器基础知识
收藏
最近发现不少小伙伴都对文章很感兴趣,所以今天继续给大家介绍文章相关的知识,本文《Spring Boot 控制器基础知识》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~
在 spring boot 中,控制器是一个包含处理 http 请求的方法的类。控制器是通过使用 restcontroller 注解一个类来创建的。
@restcontroller public class examplecontroller { private examplerepository examplerepository; private static final string template = "hello, %s!"; @getmapping("/examples/{requestedid}") public responseentity<example> findbyid(@pathvariable long requestedid) { } }
getmapping 注释用于将与字符串模式匹配的所有 get 请求路由到控制器中的方法。在您刚刚查看的代码示例中,getmapping 注释用于将所有对 url /examples/* 的 get 请求路由到 findbyid 方法。使用此代码,当请求发送到 /examples/ 时,将调用 findbyid 方法。
请求映射
还有针对其他请求方法的其他注释,例如 postmapping 和 deletemapping。它们都是从父注释 requestmapping 派生的,您可以在它们的位置使用 requestmapping,但是,当您使用 requestmapping 时,您必须指定它应该处理的 http 方法
@restcontroller public class examplecontroller { private examplerepository examplerepository; private static final string template = "hello, %s!"; @requestmapping(method="get", path="/examples/{requestedid}") public responseentity<example> findbyid(@pathvariable long requestedid) { } }
requestmapping 最常用于指定您希望 restcontroller 处理的 url。
@RestController @RequestMapping("/api/v1/examples") // This is the base path public class ExampleController { @GetMapping public String getAllExamples() { } @GetMapping("/{id}") public String getExampleById(@PathVariable("id") Long id) { } @PostMapping public String createExample() { } @DeleteMapping("/{id}") public String deleteExample(@PathVariable("id") Long id) { } }
在上面的代码片段中,通过使用 requestmapping 注解 restcontroller 类,url /api/v1/examples 充当类内所有路由的前缀。这意味着 getmapping 为 /{id} 的 getexamplebyid 方法实际上具有 getmapping 为 /api/v1/examples/{id} ,这同样适用于此类中具有与其关联的 requestmapping 的每个方法。
终于介绍完啦!小伙伴们,这篇关于《Spring Boot 控制器基础知识》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~公众号也会发布文章相关知识,快来关注吧!
版本声明 本文转载于:dev.to 如有侵犯,请联系删除