首页 > 解决方案 > 提交表单时无法将类型“java.lang.String”的值转换为所需类型“java.lang.Long”错误

问题描述

我在控制器中有这个:

@RequestMapping(
            value = "/update",
            params = {"new_profile_image"},
            method = RequestMethod.POST)
    public ModelAndView updateUserProfileImage(
            @RequestParam(value = "new_profile_image") CommonsMultipartFile newProfileImage,
            ModelMap model) {

        System.out.println("controller executed!");

        if(newProfileImage != null && !newProfileImage.isEmpty()) {
            updateService.updateUserProfileImage(newProfileImage.getBytes());
        }

        return new ModelAndView("redirect:/users/my_profile");
    }

在jsp文件中:

<form action="<c:url value='/users/update?${_csrf.parameterName}=${_csrf.token}' />" method="post"  enctype="multipart/form-data">
    <input name="new_profile_image" type="file" id="new_profile_image">

    <button type="submit" class="btn btn-primary">Update</button>
</form>

当我提交图像时,我得到

Whitelabel 错误页面 此应用程序没有显式映射 /error,因此您将其视为后备。

2020 年 2 月 8 日星期六 19:08:10 CST 出现意外错误(类型=错误请求,状态=400)。无法将“java.lang.String”类型的值转换为所需的“java.lang.Long”类型;嵌套异常是 java.lang.NumberFormatException:对于输入字符串:“更新”

该字符串"controller executed!"永远不会出现在控制台中。我在 RequestMapping 注释中更改value = "/update"了 by并且错误消息被更改为value = "/updateImage"action="<c:url value='/users/update?${_csrf.parameterName}=${_csrf.token}' />"action="<c:url value='/users/updateImage?${_csrf.parameterName}=${_csrf.token}' />"nested exception is java.lang.NumberFormatException: For input string: "updateImage"

我不知道出了什么问题,在 Eclipse 的控制台中也没有显示异常。

编辑:我忘了说控制器RequestMapping("/users")在类级别。

现在我在控制器中更改了value = "/update"value = "/updateImage"但我留action="<c:url value='/users/update?${_csrf.parameterName}=${_csrf.token}' />"在了jsp页面,错误仍然是:

Whitelabel 错误页面 此应用程序没有显式映射 /error,因此您将其视为后备。

2020 年 2 月 8 日星期六 19:08:10 CST 出现意外错误(类型=错误请求,状态=400)。无法将“java.lang.String”类型的值转换为所需的“java.lang.Long”类型;嵌套异常是 java.lang.NumberFormatException:对于输入字符串:“更新”

我猜这个请求甚至没有到达控制器。

标签: javaspringspring-mvc

解决方案


我终于通过从 中删除params属性来解决问题@RequestMapping。因此,控制器最终成为:

    @RequestMapping(
            value = "/updateImage",
            method = RequestMethod.POST)
    public ModelAndView updateUserProfileImage(
            @RequestParam(value = "new_profile_image", required = true) CommonsMultipartFile newProfileImage,
            ModelMap model) {

        System.out.println("controller executed!");

        if(newProfileImage != null && !newProfileImage.isEmpty()) {
            updateService.updateUserProfileImage(newProfileImage.getBytes());
        }

        return new ModelAndView("redirect:/users/my_profile");
    }

params在其他方法中使用了带有发布请求的属性并且它有效,我想这里的问题与请求是多部分请求有关。但我真的不知道实际问题是什么。


推荐阅读