Http статус 400, для Spring MVC Rest Api - PullRequest
1 голос
/ 08 февраля 2020

Я отправляю HTTP post запрос Spring REST API, и он возвращает http статус 400. Я проверил все, что могу, но все еще не могу решить эту проблему. Может кто-нибудь помочь мне?

Вот полезная нагрузка запроса:

{name: "ewew", описание: "addad", dateOfPurchase: "2020-02-02T19: 00 : 00.000Z ",…}

name: "ewew"
description: "addad"
dateOfPurchase: "2020-02-02T19:00:00.000Z"
paymentSource: {id: 4, title: "Cash", createdAt: 1494097200000,…}
price: 434343
residualValue: 121211
type: "Vehicle"
usefulLife: 5
        @RequestMapping(value="add",method = RequestMethod.POST)
        public ResponseEntity add(@Valid @RequestBody FixedAsset fixedAsset, BindingResult bindingResult, HttpServletRequest request){

            System.out.println("recieved");
            HashMap response = new HashMap();
            boolean success = false;
            List errors = new ArrayList();
            HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
            String message = "";
            Map data = new HashMap();

            Claims claims = (Claims) request.getAttribute("claims");
            try
            {

                User user = userService.findById((Integer) claims.get("id"));

                if (!bindingResult.hasErrors())
                {
                    if (fixedAssetService.getByName(fixedAsset.getName()) == null)
                    {
                        fixedAssetService.create(fixedAsset);
                        success = true;
                        message = "Account Type successfully added";
                        httpStatus = HttpStatus.OK;
                    } else
                    {
                        message = "Fill the form properly";
                        errors.add(new ErrorMessage("name", "Account Type with same name already exists"));
                    }

                } else
                {
                    for (FieldError error : bindingResult.getFieldErrors())
                    {
                        message = "Fill the form properly";
                        errors.add(new ErrorMessage(error.getField(), error.getDefaultMessage()));
                    }
                }

            } catch (Exception e)
            {
                errors.add(new ErrorMessage("error", e.getMessage()));
                e.printStackTrace();
            }

            response.put("success", success);
            response.put("errors", errors);
            response.put("message", message);
            response.put("data", data);
            return new ResponseEntity(response, httpStatus);

        }

Это мой класс модели:

package com.bmis.app.model;

    import javax.persistence.*;
    import java.util.Date;

    @Entity
    @Table(name = "fixed_asset")
    public class FixedAsset {

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int id;

        public int getId() {
            return this.id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public User getAddedBy() {
            return addedBy;
        }

        public void setAddedBy(User addedBy) {
            this.addedBy = addedBy;
        }

        public float getPrice() {
            return price;
        }

        public void setPrice(float price) {
            this.price = price;
        }

        public float getUsefulLife() {
            return usefulLife;
        }

        public void setUsefulLife(float usefulLife) {
            this.usefulLife = usefulLife;
        }

        public float getResidualValue() {
            return residualValue;
        }


        public void setResidualValue(float residualValue) {
            this.residualValue = residualValue;
        }

        public Account getPayment_source() {
            return payment_source;
        }

        public void setPayment_source(Account payment_source) {
            this.payment_source = payment_source;
        }

        public float getDepreciation() {
            return depreciation;
        }

        public void setDepreciation(float depreciation) {
            this.depreciation = depreciation;
        }

        public float getAccumulatedDepreciation() {
            return accumulatedDepreciation;
        }

        public void setAccumulatedDepreciation(float accumulatedDepreciation) {
            this.accumulatedDepreciation = accumulatedDepreciation;
        }

        public void setDateOfPurchase() {
            this.createdAt = new Date();
        }

        public Date getDateOfPurchase() {
            return this.createdAt;
        }


        @Column(name = "name")
        private String name;


        @Column(name = "description")
        private String description ;

        @Column(name="status")
        private String status;

        @Column(name = "type")
        private String type;


        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "added_by", referencedColumnName = "id")
        private User addedBy;

        @Column(name = "price")
        private float price;

        @Column(name = "useful_life")
        private float usefulLife;

        @Column(name ="residual_value" )
        private float residualValue;


        @Column(name="depreciation")
        private float depreciation;

        @Column(name="accumulated_depreciation")
        private float accumulatedDepreciation;

        @Column(name = "created_at")
        private Date createdAt;

        public void setCreatedAt() {
            this.createdAt = new Date();
        }

        public Date getCreatedAt() {
            return this.createdAt;
        }

        @Column(name = "date_of_purchase")
        private Date dateOfPurchase;

        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "payment_source", referencedColumnName = "id")
        private Account payment_source;

    }

Вот внешний интерфейс:

      addFixedAsset(){

        if (this.fixedAssetFormGroup.valid) {
          this.fixedAsset.name = this.f.name.value;
          this.fixedAsset.description=this.f.description.value;
          this.fixedAsset.type=this.f.type.value;
          this.fixedAsset.price=this.f.price.value;
          this.fixedAsset.usefulLife=this.f.usefulLife.value;
          this.fixedAsset.residualValue=this.f.residualValue.value;
          this.fixedAsset.dateOfPurchase=this.f.dateOfPurchase.value;
          this.fixedAsset.paymentSource=this.f.paymentSource.value;


          console.log(this.fixedAsset);


          this.fixedAssetService.create(this.fixedAsset)
          .subscribe(
            (successResponse: any) => {
                this.messageService.add({
                  severity: "info",
                  summary: "Success",
                  detail: "Fixed asset Successfully Added"
                });

             this._router.navigate(["/loggedIn", "accounts", "list-fixed-asset"]);
            },
            errorResponse => {
              console.log(errorResponse);
                this.messageService.add({
                  severity: "error",
                  summary: "Error",
                  detail: "Fixed Asset Not Added.  "

                });

            },

          );

      }

      }


     public create(fixedAsset:FixedAsset) {

        return this.http.post(this.appService.getApiUrl() + "api/fixed-asset/add", JSON.stringify(fixedAsset, this.appService.jsonStringifier));
      }
...