@RequestParam @RequestBody @PathVariable的做用

最近兩年工做的主要內容是給前端提供API接口,包括各類聯調等,項目中使用的框架有spring全家桶、Jfinal等,最近學習了下很火的SpringBoot,配合Swagger2寫Restful接口及文檔很是方便簡潔,一下是一些相關筆記。前端

@PathVariable

當使用@RequestMapping URI template 樣式映射時,@PathVariable能使傳過來的參數綁定到路由上,這樣比較容易寫出restful api,看代碼spring

@RequestMapping(value="/{id}", method=RequestMethod.GET)
    public List<Map<String, Object>> getUser(@PathVariable Integer id) {
        return userService.getUserById(id);
    }

上面這個接口可經過get請求 http://xxxxx/1111來獲得想要的數據,1111既是getUser的方法參數又是@RequestMapping的路由。若是方法參數不想寫成和路由同樣的應該怎麼辦?看代碼:json

@RequestMapping(value="/{uid}", method=RequestMethod.GET)
    public List<Map<String, Object>> getUser(@PathVariable("uid") Integer id) {
        return userService.getUserById(id);
    }

在@PathVariable後面接入「uid」就能夠了。api

@RequestParam

@RequestParam和@PathVariable的區別就在於請求時當前參數是在url路由上仍是在請求的body上,例若有下面一段代碼:restful

@RequestMapping(value="", method=RequestMethod.POST)
    public String postUser(@RequestParam(value="phoneNum", required=true) String phoneNum ) String userName) {
        userService.create(phoneNum, userName);
        return "success";
    }

這個接口的請求url這樣寫:http://xxxxx?phoneNum=xxxxxx,也就是說被@RequestParam修飾的參數最後經過key=value的形式放在http請求的Body傳過來,對比下上面的@PathVariable就很容易看出二者的區別了。app

@RequestBody

@RequestBody能把簡單json結構參數轉換成實體類,以下代碼:框架

@RequestMapping(value = "/testUser", method = RequestMethod.POST)
    public String testUser(@RequestBody User user){
        System.out.print(user.getAge());
        return "success";
    }

參數爲:post

{"id":1,"user":"pkxutao","name":"name","age":18}
相關文章
相關標籤/搜索