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