如何创建Spring Boot REST服务“类型:POST”?

时间:2018-08-15 14:56:27

标签: java spring rest spring-boot post

我是春季启动的初学者,我正在尝试创建添加两个数字(类型:POST)的REST端点,因此任何人都可以帮助我并告诉我代码中的问题在哪里? >

package demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import demo.service.ServiceAdding;

@RestController
public class DemoController {

    @Autowired
    private ServiceAdding ServiceAdding;

    @RequestMapping(value="/getNumbers", method=RequestMethod.GET)
    public ServiceAdding getNumbers() {

        ServiceAdding.setNumber1(1);
        ServiceAdding.setNumber2(3);

        return ServiceAdding;

    }

        @RequestMapping(value="/postNumbers", method=RequestMethod.POST)
        public int postNumbers (@RequestBody final ServiceAdding ServiceAdding ) {

            int sum = ServiceAdding.getNumber1() + ServiceAdding.getNumber2();
            return sum;
        }




    }

4 个答案:

答案 0 :(得分:0)

尝试使用@PostMapping而不是@RequestMapping

    @PostMapping(value = "postNumbers")
    public int postNumbers(...){
      ...
    }

答案 1 :(得分:0)

您遇到什么错误?

还可以尝试向restController添加值吗?

@RestController(value="api/v1")

@RequestMapping(value = "/getNumbers, method = RequestMethod.GET, produces = "application/json")

您还可以使用@GetMapping, @PostMapping

答案 2 :(得分:0)

听起来好像您没有执行POST请求。您如何加载该URL?

您需要具备以下条件之一:

  1. 具有执行POST的FORM的网页
  2. 使用PostMan之类的工具(或类似工具)提交发布请求。

答案 3 :(得分:0)

正确的代码如下:

@RestController
@RequestMapping("/api")
public class DemoController {

... other codes

    @RequestMapping(value="/postNumbers", method=RequestMethod.POST)
    public int postNumbers (@RequestBody SumNumbersRequest sumNumbersRequest) 
    {

        int sum = sumNumbersRequest.getNumber1() + sumNumbersRequest.getNumber2();
        return sum;
    }
}

@Data // from Lombok for getter setter
class SumNumbersRequest {
    private int number1;
    private int number2;
}

并且您应该使用Content-Type将json请求发布到url localhost:8080 / api / postNumber,如下所示:application / json:

{
   "number1":5,
   "number2":15
}