欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot之Controller的使用詳解

 更新時間:2017年08月16日 09:57:20   作者:ren-zhe  
本篇文章主要介紹了SpringBoot之Controller的使用詳解,具有一定的參考價值,感興趣的小伙伴們可以參考一下。

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

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進行測試:

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:

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

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論