你好,我想创建一个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);",然后该方法就会返回正确的账单。
正如错误所说 404 Request method 'GET' not supported
意味着你正在进行GET请求,而不是POST。
你可以利用一些工具,比如 Postman
来进行发布请求。点击 /{id}/withdraw/{amount}
通过任何浏览器都会提示一个GET请求,而不是POST请求。
问题是您发送的是一个 GET
请求到一个被配置为只接受 POST
请求。这可能会帮助你测试它们。
如果你的GET请求 -
如果你的POST请求 -