SpringBoot之Controller的使用詳解

本文介紹了 SpringBoot之Controller的使用,分享給大家,具體如下:

永善網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)建站!從網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、響應(yīng)式網(wǎng)站開發(fā)等網(wǎng)站項目制作,到程序開發(fā),運營維護。創(chuàng)新互聯(lián)建站于2013年創(chuàng)立到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗和運維經(jīng)驗,來保證我們的工作的順利進行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)建站

1.@Controller:處理http請求

2.@RestController:Spring4之后新加的注解,原來返回json需要@ResponseBody配合@Controller

3.@RequestMapping 配置url映射

1.現(xiàn)在有一個需求(即可以使用localhost:8080/hello和localhost:8080/hi都可以訪問):

@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è)置默認值以及是否必傳

3.@GetMapping–>組合注解(相當于@RequestMapping同時限定請求方法為GET 方式)

1.第一種方式:

假如http://localhost:8080/hello為請求,springboot為需要傳遞的參數(shù):http://localhost:8080/hello/spingboot,獲取此種請求的參數(shù)的方式,使用@PathVariable注解

@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; 
  } 
} 

運行程序,輸入http://localhost:8080/hello/spingboot進行測試:

SpringBoot之Controller的使用詳解

2.第二種方式:

獲取請求為http://localhost:8080/hello?params=spingboot類型的參數(shù),使用@RequesParam注解,使用方法為@RequesParam("請求中的參數(shù)名params")

@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:是否必須,默認是true,表示請求中一定要有相應(yīng)的參數(shù),否則將報錯

--defaultValue:默認值,表示如果請求中沒有同名參數(shù)時的默認值

啟動程序,輸入http://localhost:8080/hello?params=spingboot:

SpringBoot之Controller的使用詳解

對于@RequestMapping(value="/hello",method = RequestMethod.GET)可以使用:@GetMapping(value="/hello"),如果是Post的話就是用@PostMapping

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

本文名稱:SpringBoot之Controller的使用詳解
網(wǎng)頁鏈接:http://muchs.cn/article6/pgosog.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站維護、網(wǎng)站設(shè)計、App開發(fā)、搜索引擎優(yōu)化網(wǎng)站收錄、商城網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

綿陽服務(wù)器托管