【问题标题】:Model Attribute After posting DTO Object on Spring Boot在 Spring Boot 上发布 DTO 对象后的模型属性
【发布时间】:2020-01-07 17:57:58
【问题描述】:

在我的 Spring Boot 项目中,将 DTO 对象传递给我的视图,然后在提交后发布。例如。表单发布后如何访问“randomKey”?

   @GetMapping("/{userId}/edit/feature/")
   public String showEditFeature(@PathVariable("userId") Long userId, UserDto userDto,
                              Model model)
   {
    User user = userService.get(userId);

    model.addAttribute("user", user);
    model.addAttribute("randomKEy", "AnyObject");

    return "user/edit/profile";
    }

然后是我的帖子功能。

     @PostMapping("profile_update")
     public String watchFeatureUpdate(@Valid UserProfileDto UserProfileDto,
                                 BindingResult result,
                                 RedirectAttributes redirectAttributes, Model model)
     {
     Long userId = userService.updateUserProfile(userProfileDto);

     redirectAttributes.addFlashAttribute("message", "Profile features updated 
     successfully!");
     redirectAttributes.addFlashAttribute("alertClass", "alert-success");
     return "redirect:/user/view/" + userId + "/profile";
     }

【问题讨论】:

    标签: java spring spring-boot dto


    【解决方案1】:

    您需要在 HTML 页面中包含 "user/edit/profile" 作为隐藏输入每个对象属性值,以便在提交表单时将它们发回。

     <input type="hidden" name="randomKEy" value="${randomKEy}">
    
    

    请注意,即使在呈现的网页中不可见,用户仍然可以操作 HTML 内容。

    【讨论】:

    • 我试过这个,但是,它不起作用,它显示为空。但是,它作为对象显示在页面上,但不会作为字段发布。
    • 可能您还有另一个问题,因为输入超出了
      标签,或者在原始 GET 请求中未正确设置值,或者表单数据类属性名称与表单输入不匹配,但每个表单发布时发送输入(隐藏与否)。
    • jcrada,我确实经常使用隐藏字段,甚至发送用于多项选择等的数组,但没有发送用于对象的数组 AFAIK。您可以尝试确认一下。它接缝对象在传递到视图后可能无法重建。解决方案可能是使用模型(模型属性)在发布后将其取回。
    • 哦,我现在看到了问题,是的,您不能发回一个对象,您需要逐个包含其所有属性值作为输入。简单的 Http 通信无法在表单提交时神奇地序列化和反序列化您的 java 对象,因此您需要坚持键值对。
    猜你喜欢
    • 2020-11-09
    • 2018-06-15
    • 1970-01-01
    • 2020-10-23
    • 2016-07-12
    • 2018-08-05
    • 1970-01-01
    • 2018-01-24
    • 1970-01-01
    相关资源
    最近更新 更多