Angularjs Spring控制器表单提交

时间:2014-12-29 19:30:34

标签: java angularjs forms spring-mvc

Java - spring controller - Angularjs表单提交

问题出在"@RequestBody OfferForm data",当我提交表单时,我收到错误" 404错误请求"但当我用String对象替换OfferForm bean时,它工作正常并以json格式显示表单数据。

任何帮助表示感谢。

以下是我的angularjs功能代码

$scope.submitOffer = function() {
                      alert('submitOffer')
                    $http({method: 'POST', url: '/offer/submitOffer', data: $scope.formData}).
                    success(function(data, status, headers, config) {
                        $scope.successMsg = data;
                    }).
                    error(function(data, status, headers, config) {
                        if(status == 400) {
                             $scope.errMessages = data;
                        } else {
                            alert('Unexpected server error.');
                        }

                    });         
                };

以下是我的控制器代码

@RequestMapping(value="offer")
public class OfferController{
    @RequestMapping(value = "/submitOffer", method = RequestMethod.POST)
    @ResponseBody public ResponseEntity<?> postForm(@RequestBody OfferForm data) {

        System.out.println(data);

        return new ResponseEntity<String>("Offer Created", HttpStatus.OK);

    }
}

以下是我的java bean

public class OfferForm {

    private String offerType;
    private String offerTitle;


    public String getOfferType() {
        return offerType;
    }
    public void setOfferType(String offerType) {
        this.offerType = offerType;
    }
    public String getOfferTitle() {
        return offerTitle;
    }
    public void setOfferTitle(String offerTitle) {
        this.offerTitle = offerTitle;
    }

}

1 个答案:

答案 0 :(得分:1)

您的$scope.formData对象具有比Web服务预期更多的属性。

您应该向您的webservice提供一个对象,该对象最多包含两个类型为string offerTypeofferTitle的属性。 我认为您目前拥有的属性多于预期,或者您没有正确的类型,因此请求异常。

您可以在javascript中执行类似的操作,因为这两个属性是字符串:

$scope.submitOffer = function () {
    $http({
        method: 'POST',
        url: '/offer/submitOffer',
        data: {
            offerType: $scope.formData.offerType,
            offerTitle: $scope.formData.offerTitle
        }
    }).
    success(function (data, status, headers, config) {
        $scope.successMsg = data;
    }).
    error(function (data, status, headers, config) {
        if (status == 400) {
            $scope.errMessages = data;
        } else {
            alert('Unexpected server error.');
        }

    });
};