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