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

SpringBoot使用@RestController處理GET和POST請(qǐng)求的代碼詳解

 更新時(shí)間:2024年07月09日 14:14:30   作者:培根芝士  
在Spring?MVC中,@RestController注解的控制器類可以處理多種HTTP請(qǐng)求方法,包括GET和POST,所以本文就給大家詳細(xì)介紹了SpringBoot使用@RestController處理GET和POST請(qǐng)求的示例代碼,需要的朋友可以參考下

前言

在Spring MVC中,@RestController注解的控制器類可以處理多種HTTP請(qǐng)求方法,包括GET和POST。這些請(qǐng)求方法通過特定的注解來(lái)映射,比如@GetMapping用于GET請(qǐng)求,@PostMapping用于POST請(qǐng)求。這些注解是@RequestMapping的特定化版本,提供了更清晰的語(yǔ)義。

GET請(qǐng)求

GET請(qǐng)求通常用于請(qǐng)求數(shù)據(jù)。在@RestController中,你可以使用@GetMapping或@RequestMapping(method = RequestMethod.GET)來(lái)映射GET請(qǐng)求。

@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方法,這兩個(gè)方法都會(huì)處理GET請(qǐng)求,并返回簡(jiǎn)單的字符串響應(yīng)。

GET請(qǐng)求通常通過URL的查詢字符串(query string)來(lái)傳遞參數(shù)。Spring MVC提供了幾種注解來(lái)幫助你方便地獲取這些參數(shù)。

在@RestController中處理GET請(qǐng)求時(shí),@RequestParam是獲取查詢字符串參數(shù)的主要方式,

@PathVariable則用于從URL的路徑中獲取參數(shù)。

@RequestParam

@RequestParam注解用于將請(qǐng)求參數(shù)綁定到你的控制器方法的參數(shù)上。默認(rèn)情況下,請(qǐng)求參數(shù)名和參數(shù)變量名需要相同,但你可以通過value或name屬性來(lái)明確指定請(qǐng)求參數(shù)名。

@RestController  
public class MyController {  
  
    @GetMapping("/greet")  
    public String greet(@RequestParam(value = "name", required = false, defaultValue = "World") String name) {  
        return "Hello, " + name + "!";  
    }  
}

在這個(gè)例子中,greet方法通過@RequestParam注解接收一個(gè)名為name的請(qǐng)求參數(shù)。如果請(qǐng)求中沒有提供name參數(shù),那么name變量的值將是默認(rèn)值"World"。required屬性設(shè)置為false表示這個(gè)參數(shù)不是必須的。

@PathVariable

@PathVariable 是 Spring MVC 中用于將 URL 中的變量值綁定到控制器處理器方法參數(shù)上的注解。這個(gè)注解是 Spring 3.0 引入的,它允許我們從 URL 中提取變量作為方法的參數(shù)。

雖然 @PathVariable 不是直接用于GET請(qǐng)求參數(shù)的,但它經(jīng)常與GET請(qǐng)求一起使用,特別是當(dāng)你想從URL的路徑中獲取參數(shù)時(shí)。

@RestController  
public class MyController {  
  
    @GetMapping("/user/{id}")  
    public String getUserById(@PathVariable("id") Long userId) {  
        // 假設(shè)這里有一個(gè)根據(jù)userId獲取用戶信息的邏輯  
        return "User ID: " + userId;  
    }  
}

在這個(gè)例子中,{id}是一個(gè)路徑變量,它通過@PathVariable注解綁定到userId參數(shù)上。當(dāng)請(qǐng)求/user/123時(shí),userId的值將是123。

@ModelAttribute

@ModelAttribute主要用于將請(qǐng)求參數(shù)(包括查詢字符串參數(shù)、表單數(shù)據(jù)、路徑變量等)綁定到Java對(duì)象上,并將這些對(duì)象添加到模型中,以便在視圖渲染時(shí)使用。

@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方法
    }
}

默認(rèn)值和必填性

  • 對(duì)于@RequestParam,你可以通過required屬性指定參數(shù)是否是必須的,以及通過defaultValue屬性為缺失的參數(shù)提供一個(gè)默認(rèn)值。
  • 對(duì)于@PathVariable,沒有直接的required或defaultValue屬性,但你可以通過控制器方法的邏輯來(lái)處理缺失的路徑變量(盡管這通常意味著請(qǐng)求的路徑是錯(cuò)誤的)。

POST請(qǐng)求

POST請(qǐng)求通常用于提交數(shù)據(jù)給服務(wù)器。在@RestController中,你可以使用@PostMapping或@RequestMapping(method = RequestMethod.POST)來(lái)映射POST請(qǐng)求。

@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方法,這兩個(gè)方法都會(huì)處理POST請(qǐng)求。

注意,@RequestBody注解用于將請(qǐng)求體中的數(shù)據(jù)綁定到方法的參數(shù)上。

在實(shí)際應(yīng)用中,你可能會(huì)使用@RequestBody來(lái)接收一個(gè)Java對(duì)象,Spring會(huì)自動(dòng)將請(qǐng)求體中的數(shù)據(jù)映射到這個(gè)對(duì)象的屬性上。

Form請(qǐng)求

@RestController  
public class MyRestController {  
  
    @PostMapping("/submitForm")  
    public String submitForm(@RequestParam("username") String username,  
                             @RequestParam("password") String password) {  
        return "Received username: " + username + ", password: " + password;  
    }  
}

JSON請(qǐng)求

@RestController  
public class MyJsonRestController {  
  
    @PostMapping("/submitJson")  
    public String submitJson(@RequestBody MyFormObject formObject) {  
        return "Received user: " + formObject.getUsername() + ", password: " + formObject.getPassword();  
    }  
  
    // 假設(shè)你有一個(gè)MyFormObject類來(lái)接收J(rèn)SON數(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 是獲取請(qǐng)求頭中的數(shù)據(jù),通過指定參數(shù) value 的值來(lái)獲取請(qǐng)求頭中指定的參數(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請(qǐng)求的代碼詳解的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot處理GET和POST請(qǐng)求的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 解決mybatis case when 報(bào)錯(cuò)的問題

    解決mybatis case when 報(bào)錯(cuò)的問題

    這篇文章主要介紹了解決mybatis case when 報(bào)錯(cuò)的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧
    2021-02-02
  • 在SpringBoot 中從application.yml中獲取自定義常量方式

    在SpringBoot 中從application.yml中獲取自定義常量方式

    這篇文章主要介紹了在SpringBoot 中從application.yml中獲取自定義常量方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧
    2020-04-04
  • java 代理機(jī)制的實(shí)例詳解

    java 代理機(jī)制的實(shí)例詳解

    這篇文章主要介紹了java 代理機(jī)制的實(shí)例詳解的相關(guān)資料,這里說明下如何實(shí)現(xiàn)代理機(jī)制,幫助大家理解掌握這部分內(nèi)容,需要的朋友可以參考下
    2017-08-08
  • springboot整合solr的方法詳解

    springboot整合solr的方法詳解

    這篇文章主要介紹了springboot整合solr的方法詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-08-08
  • 最簡(jiǎn)單的spring boot打包docker鏡像的實(shí)現(xiàn)

    最簡(jiǎn)單的spring boot打包docker鏡像的實(shí)現(xiàn)

    這篇文章主要介紹了最簡(jiǎn)單的spring boot打包docker鏡像的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • java如何獲取用戶登錄ip、瀏覽器信息、SessionId

    java如何獲取用戶登錄ip、瀏覽器信息、SessionId

    這篇文章主要介紹了java如何獲取用戶登錄ip、瀏覽器信息、SessionId,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • maven-surefire-plugin總結(jié)示例詳解

    maven-surefire-plugin總結(jié)示例詳解

    這篇文章主要介紹了maven-surefire-plugin總結(jié),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-07-07
  • 深入探究Bean生命周期的擴(kuò)展點(diǎn)Bean Post Processor

    深入探究Bean生命周期的擴(kuò)展點(diǎn)Bean Post Processor

    在Spring框架中,Bean生命周期的管理是非常重要的一部分,在Bean的創(chuàng)建、初始化和銷毀過程中,Spring提供了一系列的擴(kuò)展點(diǎn),其中,Bean Post Processor(后處理器)是一個(gè)重要的擴(kuò)展點(diǎn),它能夠在Bean的初始化前后做一些額外的處理,本文就和大家一起深入探究
    2023-07-07
  • 從零搭建SpringBoot+MyBatisPlus快速開發(fā)腳手架

    從零搭建SpringBoot+MyBatisPlus快速開發(fā)腳手架

    這篇文章主要為大家介紹了從零搭建SpringBoot+MyBatisPlus快速開發(fā)腳手架示例教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-06-06
  • 淺談?dòng)胘ava實(shí)現(xiàn)事件驅(qū)動(dòng)機(jī)制

    淺談?dòng)胘ava實(shí)現(xiàn)事件驅(qū)動(dòng)機(jī)制

    這篇文章主要介紹了淺談?dòng)胘ava實(shí)現(xiàn)事件驅(qū)動(dòng)機(jī)制,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧
    2017-09-09

最新評(píng)論