【问题标题】:Ajax POST delete multiple items with the same name Spring MVCAjax POST 删除多个 Spring MVC 同名项目
【发布时间】:2020-01-23 03:11:41
【问题描述】:

我正在尝试在我的网络应用程序中删除多个同名项目。但是当我做 POST 时它给了我一个错误 500。

这是我的表单代码

  <form method="POST" name="deleteFormAdd" id="deleteFormAdd" enctype="multipart/form-data">
              <input type="hidden" name="_csrf" th:value="${_csrf.token}" />

                <!--Asset ID set to hidden so the User can't see it-->
                <input type="hidden" th:each="deleteCategory, itemStat : ${DeleteCategoryObject}" 
                th:name="assetID" 
                th:value="${deleteCategory.assetID}"/>

                <!-- For showing all the Asset to be deleted -->
                <input class="w3-input w3-border w3-round-large" type="text" 
                th:each="deleteCategory, itemStat : ${DeleteCategoryObject}" 
                th:name="${DeleteCategoryObject[__${itemStat.index}__].assetType}" 
                th:value="${deleteCategory.assetType}" 
                disabled="disabled"/>  

                <br></br>
                <input type="button"  class="btn btn-primary btn-block" value="Yes" th:onclick="'javascript:submitForm(\'deleteFormAdd\',\''+@{/delete-asset}+'\')'" />
                <button type="reset" onclick="window.location.href = 'manage-assets.html';" class="btn btn-default btn-block"> Cancel</button>
              </form>

提交表单 Ajax

    function submitForm(formID, url){
    var formData = new FormData($("#" + formID)[0]);
    $.ajax({
        dataType: 'json',
        url: url,
        data : formData,
        type : "POST",
        enctype : "multipart/form-data" , 
        processData : false,
        contentType : false,
        success : function(data) {
            if (data.status == 1) {
                openAlertDialog("Success", "The Asset type has been deleted!", "Continue", "manage-assets");
            } else {
                openAlertDialog("Error", data.message, "Continue", "manage-assets");
            }
        },
        error : function(data) {
            openAlertDialog("Error", data.message, "Continue", "manage-assets");
        },
    });
}

弹簧控制器

    @RequestMapping(value = "/delete-asset", method = RequestMethod.POST)
public @ResponseBody String deleteAsset(@ModelAttribute List<AssetCategory> assetCategories) {
    JsonObject result = new JsonObject();
    if (assetCategories != null && !assetCategories.isEmpty()) {
        String[] arr = new String[assetCategories.size()];
        for (int i =0; i < assetCategories.size(); i++) {
            arr[i] = assetCategories.get(i).getAssetID();
        }
        assetService.deleteAssets(arr);
        result.addProperty("result", "Success");
        result.addProperty("status", 1);
        result.addProperty("message", "Asset Deleted!");
    }
    return result.toString();
}

春季服务

    @Override
public AssetCategory deleteAssets(String[] assetID) {
    return dao.deleteAssets(assetID);
}

Spring DAO

    @Query("Delete From AssetCategory A WHERE A.assetID IN (:assetID)")
public AssetCategory deleteAssets(@Param("assetID") String[] assetID);

Spring 控制台错误

无法实例化 [java.util.List]: Specified class is an interface] 根本原因 org.springframework.beans.BeanInstantiationException: 无法实例化 [java.util.List]: 指定的类是一个接口

这是表单数据(它包含资产 ID)

【问题讨论】:

  • 但它给了我一个错误 500,需要注意的是,HTTP 500 意味着服务器端出了点问题(在你的情况下是 Spring)。请查看 spring 日志以获取更多线索,我怀疑,这可能是删除过程本身而不是 ajax。
  • 您在 Spring 控制台上收到一条错误消息。发表它。 (另外,使用List&lt;String&gt;;这对每个人来说都更容易。)
  • 我更新了帖子并将错误包含在控制台中
  • 可能不相关,但是....为什么deleteAssets(@Param("assetID") String[] assetID); 返回AssetCategory 的实例(而不是voidList - 例如它从哪里获得该实例) ?看看@Query@ModifyingdeleteBy之间的区别——baeldung.com/spring-data-jpa-deleteby有一个很好的总结。
  • 我根据 baeldung 网站更改了它。但它仍然显示错误 500。

标签: java ajax spring spring-mvc post


【解决方案1】:

您的 ajax 函数似乎有问题。请检查以下内容:

function submitForm(formID, url) {
var assetIdList = [];
var assetIdObj;
$("#" + formID).find('input[name="assetID"]').each(function () {
    assetIdObj = {};
    assetIdObj.assetID = $(this).val();
    assetIdList.push(assetIdObj);
});

$.ajax({
    dataType: 'json',
    url: url,
    data: {assetCategories: assetIdList},
    type: "POST",
    enctype: "multipart/form-data",
    processData: false,
    contentType: false,
    success: function (data) {
        if (data.status === 1) {
            openAlertDialog("Success", "The Asset type has been deleted!", "Continue", "manage-assets");
        } else {
            openAlertDialog("Error", data.message, "Continue", "manage-assets");
        }
    },
    error: function (data) {
        openAlertDialog("Error", data.message, "Continue", "manage-assets");
    },
});
}

从以下位置更新此 html 代码:

<input type="hidden" th:each="deleteCategory, itemStat : ${DeleteCategoryObject}" 
            th:name="assetID" 
            th:value="${deleteCategory.assetID}"/>

到这里:

<input type="hidden" th:each="deleteCategory, itemStat : ${DeleteCategoryObject}" 
            name="assetID" 
            th:value="${deleteCategory.assetID}"/>

【讨论】:

    【解决方案2】:

    您正在使用multipart/form-data。因此,您的请求标头具有 multipart/form-data Content-Type ,其中包含数据作为表单类型。比如键=值。

    所以只需删除@ModelAttribute 注释并将consumes 属性添加到您的映射注释。

    //if you're using spring version more than 4.3, use below @PostMapping for readability
    //@PostMapping(value = "/delete-asset", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @RequestMapping(value = "/delete-asset", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public @ResponseBody String deleteAsset(List<AssetCategory> assetCategories) {
        JsonObject result = new JsonObject();
    
        //you can use apache's commons-collection
        if (CollectionUtils.isNotEmpty(assetCategories)) {
            //and you can also use stream api
            String[] arr = assetCategories.stream()
                                   .map(AssetCategory::getAssetID)
                                   .toArray();
            assetService.deleteAssets(arr);
            result.addProperty("result", "Success");
            result.addProperty("status", 1);
            result.addProperty("message", "Asset Deleted!");
        }
        return result.toString();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      • 2016-06-19
      • 2023-03-20
      • 2012-02-16
      • 2015-02-21
      • 2016-11-28
      • 1970-01-01
      相关资源
      最近更新 更多