如何在Spring Boot应用程序中支持PUT方法?

时间:2019-03-13 12:49:58

标签: spring spring-boot

我正在使用Angular CLI和Spring Boot。

一切正常(getEmployee,deleteEmployee),但是当我想更新或创建(相同方法和相同HTML表单)某个员工时,我在HTML控制台/网络中遇到此错误:

[ERROR] message: "Request method 'PUT' not supported"

这是我的控制器:

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

    private final EmployeeServiceImpl employeeService;

    @Autowired
    public EmployeeController(EmployeeServiceImpl employeeService) {
        this.employeeService = employeeService;
    }

    @GetMapping("/employees")
    public List<Employee> getAllEmployees() {
        return employeeService.findAllEmployees();
    }

    @GetMapping("/employees/{id}")
    public ResponseEntity<Employee> getEmployeeById(@PathVariable(value = "id") Long employeeId) {
        Employee employee = employeeService.findById(employeeId).get();
        return ResponseEntity.ok().body(employee);
    }


    @PutMapping("/employees/{id}")
    public ResponseEntity<Employee> updateEmployee(@PathVariable(value = "id") Long employeeId,
                                                   @Valid @RequestBody Employee employeeDetails) {
        Employee employee = employeeService.findById(employeeId).get();

        employee.setEmailAddress(employeeDetails.getEmailAddress());
        employee.setLastName(employeeDetails.getLastName());
        employee.setFirstName(employeeDetails.getFirstName());
        employee.setStatus(employeeDetails.getStatus());
        employee.setSkills(employeeDetails.getSkills());
        final Employee updatedEmployee = employeeService.saveEmployee(employee);
        return ResponseEntity.ok(updatedEmployee);
    }

    @DeleteMapping("/employees/{id}")
    public Map<String, Boolean> deleteEmployee(@PathVariable(value = "id") Long employeeId) {
        Employee employee = employeeService.findById(employeeId).get();

        employeeService.deleteEmployee(employee);
        Map<String, Boolean> response = new HashMap<>();
        response.put("deleted", Boolean.TRUE);
        return response;
    }
}//close class

这也是我的CORSConfig:

@Configuration
public class CORSConfiguration implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedHeaders("*")
                .allowedMethods("GET", "POST", "DELETE","PUT");
    }
}//close class

在这里您可以看到我的Angular代码:

EmployeeDetail.ts

export class EmployeeDetailsComponent implements OnInit {

  @Input()
  employee: Employee;
  skills;

  constructor(
    private route: ActivatedRoute, /* holds information about the route to this instance of the EmployeeDetailsComponent */
    private location: Location,
    private employeeService: EmployeeService,
    private skillService: SkillService
  ) {
  }

  ngOnInit() {
    this.getEmployee();
    this.skillService.getSkills().subscribe(res => this.skills = res);
  }

  getEmployee(): void {
    const id = +this.route.snapshot.paramMap.get('id');
    if (id === -1) {
      this.employee = new Employee();
    } else {
      this.employeeService.getEmployee(id)
        .subscribe(employee => this.employee = employee);
    }
  }

  save(): void {
    this.employeeService.updateEmployee(this.employee)
      .subscribe(() => this.goBack());
    console.log('test', this.employee);
  }

  goBack(): void {
    this.location.back();
  }
}

当我单击保存方法时,将我重定向到服务中的Update方法;

service.ts

const httpOptions = {
  headers: new HttpHeaders({'Content-Type': 'application/json'})
};

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  private baseUrl = 'http://localhost:8080/api/employees';

  constructor(private http: HttpClient) { }


  /** GET Employees from the server */
  getEmployees(): Observable<Employee[]> {
    return this.http.get<Employee[]>(this.baseUrl);
  }

  getEmployee(id: number): Observable<Employee> {
    const url = this.baseUrl + '/' + id;
    return this.http.get<Employee>(url);
  }

  /** PUT: update the employee on the server */
  updateEmployee(employee: Employee): Observable<any> {
    return this.http.put(this.baseUrl, employee, httpOptions);
  }

  deleteEmployee(id: number): Observable<any> {
    return this.http.delete(`${this.baseUrl}/${id}`, { responseType: 'text' });
  }
}

这是我的第一个SpringBoot应用程序,也带有Angular,所以我以前从未见过此错误。

我该怎么办?

1 个答案:

答案 0 :(得分:1)

您的Angular代码显示了以下方法

  updateEmployee(employee: Employee): Observable<any> {
    return this.http.put(this.baseUrl, employee, httpOptions);
  }

您未在斜角侧包含id。但是对于您的Spring Boot端,则需要id。由于您没有传递ID,因此框架无法找到匹配方法,导致405方法不允许错误

@PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable(value = "id") Long employeeId,
                                               @Valid @RequestBody Employee employeeDetails) {
    Employee employee = employeeService.findById(employeeId).get();

    employee.setEmailAddress(employeeDetails.getEmailAddress());
    employee.setLastName(employeeDetails.getLastName());
    employee.setFirstName(employeeDetails.getFirstName());
    employee.setStatus(employeeDetails.getStatus());
    employee.setSkills(employeeDetails.getSkills());
    final Employee updatedEmployee = employeeService.saveEmployee(employee);
    return ResponseEntity.ok(updatedEmployee);
}