這篇文章給大家分享的是有關SpringBoot中常用注解是什么的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
SpringBoot 中常用注解
其中,各注解的作用為:
@PathVaribale 獲取url中的數(shù)據(jù)
@RequestParam 獲取請求參數(shù)的值
@GetMapping 組合注解,是@RequestMapping(method = RequestMethod.GET)的縮寫
@RestController是@ResponseBody和@Controller的組合注解。
@PathVaribale 獲取url中的數(shù)據(jù)
看一個例子,如果我們需要獲取Url=localhost:8080/hello/id中的id值,實現(xiàn)代碼如下:
@RestController public class HelloController { @RequestMapping(value="/hello/{id}",method= RequestMethod.GET) public String sayHello(@PathVariable("id") Integer id){ return "id:"+id; } }
@RequestParam 獲取請求參數(shù)的值
直接看一個例子,如下
@RestController public class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(@RequestParam("id") Integer id){ return "id:"+id; } }
在瀏覽器中輸入地址:localhost:8080/hello?id=1000,可以看到如下的結果:
當我們在瀏覽器中輸入地址:localhost:8080/hello?id ,即不輸入id的具體值,此時返回的結果為null。具體測試結果如下:
@GetMapping 組合注解
@GetMapping是一個組合注解,是@RequestMapping(method = RequestMethod.GET)
的縮寫。該注解將HTTP Get 映射到 特定的處理方法上。
即可以使用@GetMapping(value = “/hello”)
來代替@RequestMapping(value=”/hello”,method= RequestMethod.GET)
。即可以讓我們精簡代碼。
例子
@RestController public class HelloController { //@RequestMapping(value="/hello",method= RequestMethod.GET) @GetMapping(value = "/hello") //required=false 表示url中可以不穿入id參數(shù),此時就使用默認參數(shù) public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){ return "id:"+id; } }
@RestController
Spring4之后新加入的注解,原來返回json需要@ResponseBody
和@Controller
配合。
即@RestController
是@ResponseBody
和@Controller
的組合注解。
@RestController public class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(){ return "hello"; } }
與下面的代碼作用一樣
@Controller @ResponseBody public class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(){ return "hello"; } }
注解@RequestParam 和 @PathVarible的區(qū)別
@RequestParam是請求中的參數(shù)。如get?id=1
@PathVarible是請求路徑中的變量如 get/id=1
感謝各位的閱讀!關于“SpringBoot中常用注解是什么”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
當前題目:SpringBoot中常用注解是什么-創(chuàng)新互聯(lián)
轉載注明:http://www.rwnh.cn/article16/pjidg.html
成都網站建設公司_創(chuàng)新互聯(lián),為您提供App開發(fā)、商城網站、動態(tài)網站、電子商務、定制網站、域名注冊
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)