@RestController
@RequestMapping(value = "demo")
public class TestController {
//Content-Type:application/x-www-form-urlencoded;表單送出form-data
@PostMapping("/demo1")
public String test1(@RequestParam("id") Integer id,@RequestParam("name") String name) {
System.out.println("test1......");
return Integer.valueOf(id) + ":" + name;
}
//Content-Type:application/x-www-form-urlencoded
@PostMapping("/demo2")
public String test2(DemoUser demoUser) {
System.out.println("test2......");
return Integer.valueOf(demoUser.getId()) + ":" + demoUser.getName();
}
//Content-Type:application/json
@PostMapping("/demo3")
public String test3(@RequestBody DemoUser demoUser) {
System.out.println("test3......");
return Integer.valueOf(demoUser.getId()) + ":" + demoUser.getName();
}
//Content-Type:application/x-www-form-urlencoded;form-data表單;application/json(用@RequestBody接收)都可以
@DeleteMapping("/demo4")
public String test4(@RequestParam("id") Integer id,@RequestParam("name") String name) {
System.out.println("test4......");
return Integer.valueOf(id) + ":" + name;
}
//http:localhost:8080/demo/1
@GetMapping("/{id}")
public String test5(@PathVariable("id") Integer id) {
System.out.println("test5....");
return String.valueOf(id);
}
//application/json
@PostMapping("/demo6")
public String test6(@RequestBody Map<String,Object> map) {
System.out.println("test6...............");
return map.get("id") + ":" + map.get("name");
}
}
以上是示例代碼,總結如下
content-type,表示你前端用那種方式傳參。
如果application/json使用json傳參,那麼你背景就需要用@RequstBody來接受參數。
如果用form-data表單方式傳參,那麼你背景可以直接用一個vo對象接收,或者你直接使用@RequestParam參數來接受
最後一個例子中,http:localhost:8080/demo/{id}–這種方式傳參,你需要@PathVariable來接受參數