SpringBoot實現前后端數據交互、json數據交互、Controller接收參數的幾種常用方式


1.獲取參數的集中常見注解

  • @PathVariable:一般我們使用URI template樣式映射使用,即url/{param}這種形式,也就是一般我們使用的GET,DELETE,PUT方法會使用到的,我們可以獲取URL后所跟的參數。
  • @RequestParam:一般我們使用該注解來獲取多個參數,在()內寫入需要獲取參數的參數名即可,一般在PUT,POST中比較常用。
  • @RequestBody:該注解和@RequestParam殊途同歸,我們使用該注解將所有參數轉換,在代碼部分在一個個取出來,也是目前我使用到最多的注解來獲取參數

2.獲取請求路徑參數

  1. get請求,url路徑傳參
    get請求一般通過url傳參,如:

http://localhost:8080/piano/add?brand="xinde" & price = "1200"
后端要獲取這些參數,可以使用@RequestParam注解


@RestController
public class HelloController {
    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(@RequestParam Integer id){
        return "id:"+id;
    }

  1. get請求,url路徑參數

http://localhost:8080/piano/xinde/buyaoq/1200

后端可以使用@PathVariable接收路徑參數

@RestController
public class HelloController {
    @RequestMapping(value="/piano/{brand}/{price}",method= RequestMethod.GET)
    public String sayHello(@PathVariable("price") Integer id,@PathVariable("name") String name){
        return "id:"+id+" name:"+name;
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM