Spring RestController Post方法不起作用,但get方法有效

时间:2019-11-20 20:32:49

标签: angular spring-boot spring-restcontroller

这是我的RestController,get方法有效,但post方法无效。


@RestController
@RequestMapping("/workpackages")
public class RESTWorkPackageController {

    @Autowired
    private WorkPackageService service;

    @GetMapping()
    public DataTableResponse<WorkPackage> findWorkPackage(DataTableRequest dataTableRequest) {
        return service.findWorkPackage(dataTableRequest);
    }

    @PostMapping()
    public ResponseEntity<?> addWorkPackage(@RequestBody WorkPackage workPackage) {
        WorkPackage w = service.addWorkPackage(workPackage);
        URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(w.getId()).toUri();
        return ResponseEntity.created(location).build();
    }


}

这是我对角度客户端的要求:

addWorkpackage(workpackage: WorkPackage): Observable<WorkPackage> {
        return this.http.post<WorkPackage>(`${URL.Workpackages}/`, workpackage);
    }

    getWorkpackages(request: DataTableRequest): Observable<DataTableResponse> {
        return this.http.get<DataTableResponse>(`${URL.Workpackages}/`, {params: request as any});
    }

获取请求有效,但未调用post方法。 为什么会这样?

更新: 这是WorkPackage类的Java代码:

Entity
@Table(name = "workpackages")
@Getter
@Setter
@NoArgsConstructor
public class WorkPackage {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "workpackage_id")
    private Long id;

    @NonNull
    @Column(name = "workpackage_number", unique = true)
    @Size(max = 8)
    private String workpackageNumber;

    @Column(name = "title")
    @Size(max = 50)
    private String title;

    @Column(name = "objective")
    @Size(max = 250)
    private String objective;

    @ManyToOne
    @JoinColumn(name = "project_id")
    private Project project;
}

这是JS类中的WorkPackage

export class WorkPackage {

    constructor(workpackage?) {
        workpackage = workpackage || {};
        this.id = workpackage.id || null;
        this.workpackageNumber = workpackage.workpackageNumber || '';
        this.objective = workpackage.objective || '';
        this.project = workpackage.project || null;
    }

    id: number;
    workpackageNumber: string;
    title: string;
    objective: string;
    project: Project;
}

这是一个JSON正文示例:

{“ id”:空, “ workpackageNumber”:“ 21”, “ objective”:“ test”, “ project”:{“ id”:1,“ title”:“ test”,“ acronym”:“ tt”,“ code”:“ 022”,“ startDate”:“ 2017-03-13”,“ endDate” :“ 2017-04-17”,“所有者”:null},“标题”:“ Prova wp”}

2 个答案:

答案 0 :(得分:0)

可能是“ Spring Boot”无法将请求主体与您的模型映射,您在服务器控制台中看到了什么?

答案 1 :(得分:0)

您可以从Spring引导服务中发布错误日志吗?最可能的情况是请求中的workpackage json不符合服务器端的WorkPackage pojo。

您可以发布POST请求的示例JSON正文以及WorkPackage类的Java代码吗?