【问题标题】:HttpRequestMethodNotSupportedException: Request method 'POST' not supported in Spring APIHttpRequestMethodNotSupportedException:Spring API 不支持请求方法“POST”
【发布时间】:2021-11-24 18:16:56
【问题描述】:

我想为我的 Employee 实体(表)构建一个 API,当我尝试通过 id 或在 URL 中没有 id 的 GET 请求时,它可以工作。但是当我尝试 POST、PUT、PATCH 或 DELETE 请求时,它将出现 405 错误。 POST 请求看起来像这样

2021-11-24 18:42:59.517 DEBUG 4756 [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet         :"ERROR" dispatch for POST "/error", parameters={}
2021-11-24 18:42:59.520 WARN 4756---[nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]
2021-11-24 18:42:59.520 DEBUG 4756 [nio-8080-exec-6]o.s.web.servlet.DispatcherServlet          :Exiting from "ERROR" dispatch, status 405

api-controlle 类看起来像

package com.miki.pma.api.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.miki.pma.dao.EmployeeRepository;
import com.miki.pma.entity.Employee;

@RestController
@RequestMapping("/app-api/employees")
public class EmployeeApiController {
    
    @Autowired
    EmployeeRepository empRepo;
    
    @GetMapping()
    public Iterable<Employee> getEmployees(){
        return empRepo.findAll();
    }
    @GetMapping("/{id}")
    public Employee getEmployeeById(@PathVariable("id") Long id) {
        return empRepo.findById(id).get();
    }
    @PostMapping(consumes="application/json")
    @ResponseStatus(HttpStatus.CREATED)
    public Employee create(@RequestBody Employee employee) {
        return empRepo.save(employee);
    }
    @PutMapping(consumes="application/json")
    @ResponseStatus(HttpStatus.OK)
    public Employee update(@RequestBody Employee employee) {
        return empRepo.save(employee);
    }
    
    @PatchMapping(value = "/{id}",consumes="application/json")
    public Employee partialUpdate(@PathVariable("id") Long id, @RequestBody Employee pathEmployee) {
        
        Employee emp= empRepo.findById(id).get();
        
        if(pathEmployee.getEmail()!= null) {
            emp.setEmail(pathEmployee.getEmail());
        }
        if(pathEmployee.getFirstName()!= null) {
            emp.setFirstName(pathEmployee.getFirstName());  
        }
        if(pathEmployee.getLastname()!= null) {
            emp.setLastname(pathEmployee.getLastname());
        }
        return empRepo.save(emp);
    }
    @DeleteMapping(value="/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable("id") Long id) {

        empRepo.deleteById(id);
    }

}

Employee 实体类如下所示

package com.miki.pma.entity;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.SequenceGenerator;
import javax.validation.constraints.Email;
import javax.validation.constraints.Size;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.sun.istack.NotNull;

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy= GenerationType.SEQUENCE, generator="employee_seq")
    @SequenceGenerator(name = "employee_seq", allocationSize = 1)
    private long employeeId;
    
    @NotNull
    @Size(min=2, max=50)
    private String firstName;
    
    @NotNull
    @Size(min=1, max=50)
    private String lastname;
    
    @NotNull
    @Email
    @Column(unique=true)
    private String email;
    
    @ManyToMany(cascade= {CascadeType.DETACH,CascadeType.MERGE,CascadeType.PERSIST, CascadeType.REFRESH}
    , fetch= FetchType.LAZY)
    @JoinTable(name="employee_project",
            joinColumns=@JoinColumn(name="employee_id"),
            inverseJoinColumns=@JoinColumn(name="project_id"))
    @JsonIgnore
    private List<Project> projects;
    
    
    public List<Project> getProjects() {
        return projects;
    }
    public void setProjects(List<Project> projects) {
        this.projects = projects;
    }
    public Employee() {
        super();
    }
    public Employee(String firstName, String lastname, String email) {
        super();
        this.firstName = firstName;
        this.lastname = lastname;
        this.email = email;
    }
    public long getEmployeeId() {
        return employeeId;
    }
    public void setEmployeeId(long employeeId) {
        this.employeeId = employeeId;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

}


您可以在此图片链接中看到我尝试过的发布请求,请查看 Post request from arch

那么我该如何使用 POST、PUT、DELETE 和 PATCH 请求

【问题讨论】:

  • 你能显示你发送的 POST 请求吗?
  • 我已经为 POST 请求添加了一个链接,现在检查一下。

标签: java spring spring-boot rest spring-mvc


【解决方案1】:

据我所知,HttpRequestMethodNotSupportedException 发生在您的端点被识别但您发送wrong REST action type 时。例如,您使用 POST 发送请求,它实际上是一个 GET 端点。 此外,我没有看到为 POST/PUT/PATCH 定义的任何特定端点。休息端点必须是动作动词,例如baseURL/create -> 创建资源等等..

【讨论】:

    猜你喜欢
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 2020-10-29
    • 2016-05-02
    相关资源
    最近更新 更多