spring @DeleteMapping无法运作,错误消息:异常错误:不支持请求方法'DELETE'

f4t66c6m  于 2022-11-28  发布在  Spring
关注(0)|答案(2)|浏览(482)

所以我必须做一个CRUD应用程序,当在postman上运行时,显示的错误是405,方法不允许。在尝试“spring.mvc.hiddenmethod.filter.enabled:true”application.properties在使用postman进行测试时,代码仍然显示相同的错误。
这是控制器

@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);
        
    }
}

这就是服务

@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);
    }

}

在尝试其他put post和get方法时,代码运行得非常好。但这是我发现405错误的唯一地方。

dhxwm5r4

dhxwm5r41#

试试这个

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

wgx48brx2#

请输入您请求的网址,您可能输入了错误的网址,正确的网址应该是:

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

1是要删除的ID。

相关问题