在Spring引导中,请求方法 "GET "不支持 "POST "映射。

问题描述 投票:0回答:2

你好,我想创建一个POST方法,我一直收到 "404请求方法'GET'不支持 "的错误。下面我将发布我的Rest控制器,下面我将发布我的服务类。唯一不工作的是@PostMapping方法。

@RequestMapping("/ATM")
public class ATMController {

    private ATMService atmService;

    @Autowired
    public ATMController(ATMService atmService) {
        this.atmService = atmService;
    }

    @GetMapping(path = "/{id}")
    public ATM getATMById(@PathVariable long id){
        return atmService.getByID(id);
    }

    @PostMapping(path = "/{id}/withdraw/{amount}")
    public List<Bill> withdrawMoney(@PathVariable long id,@PathVariable float amount){
       return atmService.withdrawMoney(id,amount);
    }
}
@Service
public class ATMService {

    private ATMRepository atmRepository;
    private BillRepository billRepository;

    @Autowired
    public ATMService(ATMRepository atmRepository, BillRepository billRepository) {
        this.atmRepository = atmRepository;
        this.billRepository = billRepository;
    }

    public void save(ATM atm) {
        atmRepository.save(atm);
    }

    public ATM getByID(Long id) {
        return atmRepository.findById(id).get();
    }

    public List<Bill> getBillList(Long id) {
        return atmRepository.findById(id).get().getBillList();
    }

    @Transactional
    public List<Bill> withdrawMoney(Long id, float amount) {
        List<Bill> allBills = getBillList(id);
        List<Bill> billsToWithdraw = new ArrayList<>();
        float amountTransferred = 0;

        for (Bill bill : allBills) {
            if (bill.getValue() == 100) {
                billsToWithdraw.add(bill);
                amountTransferred += bill.getValue();
            }
            if (amountTransferred == amount) {
                for (Bill billToWithdraw : billsToWithdraw) {
                    billRepository.delete(billToWithdraw);
                }
                return billsToWithdraw;
            }
        }
        return null;
    }
}

我没看出问题所在,我试着切换到@GetMapping,并删除了实际事务 "billRepository.delete(billToWithdraw);",然后该方法就会返回正确的账单。

java spring spring-boot rest spring-restcontroller
2个回答
1
投票

正如错误所说 404 Request method 'GET' not supported 意味着你正在进行GET请求,而不是POST。

你可以利用一些工具,比如 Postman 来进行发布请求。点击 /{id}/withdraw/{amount} 通过任何浏览器都会提示一个GET请求,而不是POST请求。


0
投票

问题是您发送的是一个 GET 请求到一个被配置为只接受 POST 请求。这可能会帮助你测试它们。

如何测试

如果你的GET请求 -

  1. 你可以直接从浏览器地址栏中查看api。输入api,然后按回车键,就这么简单。
  2. 你可以使用一个工具,如Postman,SoapUI等来发送一个GET请求,你可以写一个html表单,action="get mapping uri",method="GET"。
  3. 你可以写一个html表单,action="get mapping uri "和method="GET"
  4. 如果你的API使用任何文档或设计工具,如swagger,你可以从它的界面进行测试。

如果你的POST请求 -

  1. 你不能直接从浏览器地址栏检查api。
  2. 你可以使用一个工具,如Postman,SoapUI来发送POST请求。
  3. 你可以写一个html表单,action="post mapping uri",method="POST"。
  4. 如果你的API使用任何文档或设计工具,如swagger,你可以从它的界面进行测试。
© www.soinside.com 2019 - 2024. All rights reserved.