SpringBoot使用@RestController處理GET和POST請求的代碼詳解
前言
在Spring MVC中,@RestController注解的控制器類可以處理多種HTTP請求方法,包括GET和POST。這些請求方法通過特定的注解來映射,比如@GetMapping用于GET請求,@PostMapping用于POST請求。這些注解是@RequestMapping的特定化版本,提供了更清晰的語義。
GET請求
GET請求通常用于請求數(shù)據(jù)。在@RestController中,你可以使用@GetMapping或@RequestMapping(method = RequestMethod.GET)來映射GET請求。
@RestController public class MyController { @GetMapping("/greeting") public String greeting() { return "Hello, World!"; } // 或者使用@RequestMapping @RequestMapping(value = "/hello", method = RequestMethod.GET) public String hello() { return "Hi there!"; } }
在上面的例子中,/greeting和/hello路徑分別映射到greeting和hello方法,這兩個方法都會處理GET請求,并返回簡單的字符串響應(yīng)。
GET請求通常通過URL的查詢字符串(query string)來傳遞參數(shù)。Spring MVC提供了幾種注解來幫助你方便地獲取這些參數(shù)。
在@RestController中處理GET請求時,@RequestParam是獲取查詢字符串參數(shù)的主要方式,
@PathVariable則用于從URL的路徑中獲取參數(shù)。
@RequestParam
@RequestParam注解用于將請求參數(shù)綁定到你的控制器方法的參數(shù)上。默認情況下,請求參數(shù)名和參數(shù)變量名需要相同,但你可以通過value或name屬性來明確指定請求參數(shù)名。
@RestController public class MyController { @GetMapping("/greet") public String greet(@RequestParam(value = "name", required = false, defaultValue = "World") String name) { return "Hello, " + name + "!"; } }
在這個例子中,greet方法通過@RequestParam注解接收一個名為name的請求參數(shù)。如果請求中沒有提供name參數(shù),那么name變量的值將是默認值"World"。required屬性設(shè)置為false表示這個參數(shù)不是必須的。
@PathVariable
@PathVariable 是 Spring MVC 中用于將 URL 中的變量值綁定到控制器處理器方法參數(shù)上的注解。這個注解是 Spring 3.0 引入的,它允許我們從 URL 中提取變量作為方法的參數(shù)。
雖然 @PathVariable 不是直接用于GET請求參數(shù)的,但它經(jīng)常與GET請求一起使用,特別是當你想從URL的路徑中獲取參數(shù)時。
@RestController public class MyController { @GetMapping("/user/{id}") public String getUserById(@PathVariable("id") Long userId) { // 假設(shè)這里有一個根據(jù)userId獲取用戶信息的邏輯 return "User ID: " + userId; } }
在這個例子中,{id}是一個路徑變量,它通過@PathVariable注解綁定到userId參數(shù)上。當請求/user/123時,userId的值將是123。
@ModelAttribute
@ModelAttribute主要用于將請求參數(shù)(包括查詢字符串參數(shù)、表單數(shù)據(jù)、路徑變量等)綁定到Java對象上,并將這些對象添加到模型中,以便在視圖渲染時使用。
@RestController public class MyController { @GetMapping("/search") public String search( @ModelAttribute MySearchParams searchParams) { return "Searching for: " + searchParams.getQuery(); } // 假設(shè)MySearchParams類如下 static class MySearchParams { private String query; // 省略getter和setter方法 } }
默認值和必填性
- 對于@RequestParam,你可以通過required屬性指定參數(shù)是否是必須的,以及通過defaultValue屬性為缺失的參數(shù)提供一個默認值。
- 對于@PathVariable,沒有直接的required或defaultValue屬性,但你可以通過控制器方法的邏輯來處理缺失的路徑變量(盡管這通常意味著請求的路徑是錯誤的)。
POST請求
POST請求通常用于提交數(shù)據(jù)給服務(wù)器。在@RestController中,你可以使用@PostMapping或@RequestMapping(method = RequestMethod.POST)來映射POST請求。
@RestController public class MyController { // 使用@PostMapping @PostMapping("/submit") public ResponseEntity<String> submitData(@RequestBody String data) { // 處理數(shù)據(jù)... return ResponseEntity.ok("Data received: " + data); } // 或者使用@RequestMapping @RequestMapping(value = "/postData", method = RequestMethod.POST) public ResponseEntity<String> postData(@RequestBody String data) { // 處理數(shù)據(jù)... return ResponseEntity.ok("Data posted: " + data); } }
在上面的例子中,/submit和/postData路徑分別映射到submitData和postData方法,這兩個方法都會處理POST請求。
注意,@RequestBody注解用于將請求體中的數(shù)據(jù)綁定到方法的參數(shù)上。
在實際應(yīng)用中,你可能會使用@RequestBody來接收一個Java對象,Spring會自動將請求體中的數(shù)據(jù)映射到這個對象的屬性上。
Form請求
@RestController public class MyRestController { @PostMapping("/submitForm") public String submitForm(@RequestParam("username") String username, @RequestParam("password") String password) { return "Received username: " + username + ", password: " + password; } }
JSON請求
@RestController public class MyJsonRestController { @PostMapping("/submitJson") public String submitJson(@RequestBody MyFormObject formObject) { return "Received user: " + formObject.getUsername() + ", password: " + formObject.getPassword(); } // 假設(shè)你有一個MyFormObject類來接收JSON數(shù)據(jù) static class MyFormObject { private String username; private String password; // 省略getter和setter方法 } }
上傳圖片
@PostMapping(value = "/uploadFile", name = "上傳文件") public String uploadImage(MultipartFile file) { //獲取文件原名 String fileName = file.getOriginalFilename(); //設(shè)置上傳路徑 //判斷上傳路徑是否存在,不存在則創(chuàng)建目錄 File fileDir = new File(realPath); if (!fileDir.exists()) { fileDir.mkdirs(); } String strYmd= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); File fileYmdDir = new File(realPath + "/" + strYmd); if (!fileYmdDir.exists()) { fileYmdDir.mkdirs(); } fileName = getFileName(fileName); String outputPath = ""; //上傳文件 try { outputPath = realPath +"/"+strYmd+ "/" + fileName; InputStream input = file.getInputStream(); FileOutputStream fos = new FileOutputStream(outputPath); IOUtils.copy(input, fos); } catch (Exception e) { System.out.println(e.getMessage()); return null; } System.out.println("uploadFile:"+outputPath); return outputPath; }
@RequestHeader
@RequestHeader 是獲取請求頭中的數(shù)據(jù),通過指定參數(shù) value 的值來獲取請求頭中指定的參數(shù)值。其他參數(shù)用法和 @RequestParam 完全一樣。
@ResponseBody @GetMapping("/RequestHeader") public Map test(@RequestHeader("host") String host){ Map map = new HashMap(); map.put("header", host); return map; }
@ResponseBody @GetMapping("/RequestHeader") public Map test(@RequestHeader Map<String, String> headers){ Map map = new HashMap(); map.put("headers", headers); return map; }
以上就是SpringBoot使用@RestController處理GET和POST請求的代碼詳解的詳細內(nèi)容,更多關(guān)于SpringBoot處理GET和POST請求的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
在SpringBoot 中從application.yml中獲取自定義常量方式
這篇文章主要介紹了在SpringBoot 中從application.yml中獲取自定義常量方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04最簡單的spring boot打包docker鏡像的實現(xiàn)
這篇文章主要介紹了最簡單的spring boot打包docker鏡像的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10java如何獲取用戶登錄ip、瀏覽器信息、SessionId
這篇文章主要介紹了java如何獲取用戶登錄ip、瀏覽器信息、SessionId,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11maven-surefire-plugin總結(jié)示例詳解
這篇文章主要介紹了maven-surefire-plugin總結(jié),本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07深入探究Bean生命周期的擴展點Bean Post Processor
在Spring框架中,Bean生命周期的管理是非常重要的一部分,在Bean的創(chuàng)建、初始化和銷毀過程中,Spring提供了一系列的擴展點,其中,Bean Post Processor(后處理器)是一個重要的擴展點,它能夠在Bean的初始化前后做一些額外的處理,本文就和大家一起深入探究2023-07-07從零搭建SpringBoot+MyBatisPlus快速開發(fā)腳手架
這篇文章主要為大家介紹了從零搭建SpringBoot+MyBatisPlus快速開發(fā)腳手架示例教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06