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)//使用集合設置 public String say(){ return "Hello Spring Boot"; } }
SpringBoot獲取請求參數(shù)
1.@PathVariable–>獲取url中的數(shù)據(jù)
2.@ReqeustParam–>獲取請求參數(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,表示請求中一定要有相應的參數(shù),否則將報錯
--defaultValue:默認值,表示如果請求中沒有同名參數(shù)時的默認值
啟動程序,輸入http://localhost:8080/hello?params=spingboot:
對于@RequestMapping(value="/hello",method = RequestMethod.GET)可以使用:@GetMapping(value="/hello"),如果是Post的話就是用@PostMapping
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
springboot2.x默認使用的代理是cglib代理操作
這篇文章主要介紹了springboot2.x默認使用的代理是cglib代理操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08springboot 實現(xiàn)mqtt物聯(lián)網(wǎng)的示例代碼
這篇文章主要介紹了springboot 實現(xiàn)mqtt物聯(lián)網(wǎng),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03Java實現(xiàn)Fibonacci(斐波那契)取余的示例代碼
這篇文章主要介紹了Java實現(xiàn)Fibonacci取余的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-03-03詳解Spring Boot實戰(zhàn)之Filter實現(xiàn)使用JWT進行接口認證
本篇文章主要介紹了詳解Spring Boot實戰(zhàn)之Filter實現(xiàn)使用JWT進行接口認證,具有一定的參考價值,有興趣的可以了解一下2017-07-07