天天看点

@DeleteMapping和@PostMapping和@GetMapping和Content-Type使用记录

@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来接受参数
           

继续阅读