Home > Back-end >  @DeleteMapping not working. Error message: org.springframework.web.HttpRequestMethodNotSupportedExce
@DeleteMapping not working. Error message: org.springframework.web.HttpRequestMethodNotSupportedExce

Time:11-22

So I have to make a CRUD application and when run on postman, the error being shown is 405, Method not allowed. Upon trying "spring.mvc.hiddenmethod.filter.enabled: true" in the application.properties file, the code still showed the same error when tested using postman.

This is the controller

@RestController
@RequestMapping("/employees")

public class EmpController {
    
    @Autowired
    private EmpService empService;
    @Autowired
    private EmpRepository empRepo;
    @GetMapping("")
    public List<Employee> getAllEmployees()
        {
        return empService.getAllEmployees();
        }
    
    @PostMapping("")
    public void addEmployee(@RequestBody Employee emp) 
    {
        empService.addEmployee(emp);
    }
    
    @PutMapping("/{id}")
    public void updateEmployee(@PathVariable String id,@RequestBody Employee emp)
    {
        empService.updateEmployee(id,emp);
    }
    
    @DeleteMapping(path="/{id}")
    public void deleteEmployee(@PathVariable String id) {
        System.out.println("Delete function");
        empService.deleteEmployee(id);
        
    }
}

This is the service

@org.springframework.stereotype.Service
public class EmpService {
    @Autowired
    public EmpRepository empRepo;
    
    public List<Employee> getAllEmployees(){
        List<Employee> employees = new ArrayList<>();
        empRepo.findAll().forEach(employees::add);
        return employees;
    }
    public void addEmployee(Employee emp) {
        empRepo.save(emp);
    }
    public void updateEmployee(String id, Employee emp) {
        empRepo.save(emp);
        
    }
    public void deleteEmployee(String id) {
        empRepo.deleteById(id);
    }

}

on trying the the other put post and get methods the code was working perfectly fine. But this is the only place where I found the 405 error.

CodePudding user response:

Try this

@DeleteMapping(path="/{id}")
public void deleteEmployee(@PathVariable("id") String id) {
    System.out.println("Delete function");
    empService.deleteEmployee(id);
    
}

CodePudding user response:

Can you put your request url here? Maybe you used wrong url. The right url should be:

http://{host}:{port}/employees/1

1 is the id you want to delete.

  • Related