本文介紹了 springboot之controller的使用,分享給大家,具體如下:
1.@controller:處理http請求
2.@restcontroller:spring4之后新加的注解,原來返回json需要@responsebody配合@controller
3.@requestmapping 配置url映射
1.現(xiàn)在有一個需求(即可以使用localhost:8080/hello和localhost:8080/hi都可以訪問):
1
|
2
3
4
5
6
7
|
@restcontroller public class hellocontroller { @requestmapping (value={ "/hello" , "hi" },method = requestmethod.get) //使用集合設(shè)置 public string say(){ return "hello spring boot" ; } } |
springboot獲取請求參數(shù)
1.@pathvariable–>獲取url中的數(shù)據(jù)
2.@reqeustparam–>獲取請求參數(shù)的值,可以設(shè)置默認(rèn)值以及是否必傳
3.@getmapping–>組合注解(相當(dāng)于@requestmapping同時限定請求方法為get 方式)
1.第一種方式:
假如http://localhost:8080/hello為請求,springboot為需要傳遞的參數(shù):http://localhost:8080/hello/spingboot,獲取此種請求的參數(shù)的方式,使用@pathvariable注解
1
|
2
3
4
5
6
7
|
@restcontroller public class hellocontroller { @requestmapping ( "/hello/{params}" ) //獲取請求為 http://localhost:8080/hello/xxx 類型的參數(shù) public string hello( @pathvariable ( "params" ) string paramsstr) { //聲明一個變量接收請求中的參數(shù) return "parameter is " +paramsstr; } } |
運(yùn)行程序,輸入http://localhost:8080/hello/spingboot進(jìn)行測試:
2.第二種方式:
獲取請求為http://localhost:8080/hello?params=spingboot類型的參數(shù),使用@requesparam注解,使用方法為@requesparam("請求中的參數(shù)名params")
1
|
2
3
4
5
6
7
8
|
@restcontroller public class hellocontroller { //獲取請求為 http://localhost:8080/hello ?xxx=xxx類型的參數(shù) @requestmapping ( "/hello" ) public string hello( @requestparam ( "params" ) string paramsstr) { //requestparam中的參數(shù)名稱與請求中參數(shù)名稱要一致 return "parameter is " +paramsstr; } } |
如:@requestparam(value="item_id",required=true) string id
@requestparam中的其他屬性:
--required:是否必須,默認(rèn)是true,表示請求中一定要有相應(yīng)的參數(shù),否則將報錯
--defaultvalue:默認(rèn)值,表示如果請求中沒有同名參數(shù)時的默認(rèn)值
啟動程序,輸入http://localhost:8080/hello?params=spingboot:
對于@requestmapping(value="/hello",method = requestmethod.get)可以使用:@getmapping(value="/hello"),如果是post的話就是用@postmapping
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://blog.csdn.net/qq_35508033/article/details/71893371?utm_source=gold_browser_extension