本篇文章將介紹幾種springboot 中常用注解
其中,各注解的作用為:
@pathvaribale 獲取url中的數據
@requestparam 獲取請求參數的值
@getmapping 組合注解,是@requestmapping(method = requestmethod.get)的縮寫
@restcontroller是@responsebody和@controller的組合注解。
@pathvaribale 獲取url中的數據
看一個例子,如果我們需要獲取url=localhost:8080/hello/id中的id值,實現代碼如下:
1
2
3
4
5
6
7
8
|
@restcontroller public class hellocontroller { @requestmapping (value= "/hello/{id}" ,method= requestmethod.get) public string sayhello( @pathvariable ( "id" ) integer id){ return "id:" +id; } } |
@requestparam 獲取請求參數的值
直接看一個例子,如下
1
2
3
4
5
6
7
8
|
@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)
。即可以讓我們精簡代碼。
例子
1
2
3
4
5
6
7
8
9
|
@restcontroller public class hellocontroller { //@requestmapping(value="/hello",method= requestmethod.get) @getmapping (value = "/hello" ) //required=false 表示url中可以不穿入id參數,此時就使用默認參數 public string sayhello( @requestparam (value= "id" ,required = false ,defaultvalue = "1" ) integer id){ return "id:" +id; } } |
@restcontroller
spring4之后新加入的注解,原來返回json需要@responsebody
和@controller
配合。
即@restcontroller
是@responsebody
和@controller
的組合注解。
1
2
3
4
5
6
7
8
|
@restcontroller public class hellocontroller { @requestmapping (value= "/hello" ,method= requestmethod.get) public string sayhello(){ return "hello" ; } } |
與下面的代碼作用一樣
1
2
3
4
5
6
7
8
9
|
@controller @responsebody public class hellocontroller { @requestmapping (value= "/hello" ,method= requestmethod.get) public string sayhello(){ return "hello" ; } } |
注解@requestparam 和 @pathvarible的區別
@requestparam是請求中的參數。如get?id=1
@pathvarible是請求路徑中的變量如 get/id=1
總結
以上所述是小編給大家介紹的springboot 中常用注解及各種注解作用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://www.cnblogs.com/xubb/p/8492259.html