使用spring mvc提交/绑定部分对象 [英] Submitting / binding partial objects with spring mvc

查看:144
本文介绍了使用spring mvc提交/绑定部分对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring MVC绑定机制很强大,但我现在面临一个小问题,我想知道如何解决:

The Spring MVC binding mechanism is powerful, but I'm now confronted with a trivial issue that I wonder how to resolve:


  • 用户 JPA实体,也用于绑定和验证(即在所有层中)

  • 编辑个人资料页面,那不应该改变密码或其他一些实体属性

  • User JPA entity, that is used for the binding and validation as well (i.e. throughout all layers)
  • "Edit profile" page, that is not supposed to change the password or some other entity properties

我能想到的两种方式:


  1. 使用相同的对象

  1. Using the same object


  • 使用 @InitBinder 配置不允许的属性列表

  • 获取目标用户(按id)

  • 然后使用反射实用程序(BeanUtils)将提交的对象复制到目标对象,但忽略 null 值 - 即未提交的字段

  • use @InitBinder to configure a list of disallowed properties
  • obtain the target user (by id)
  • then use a reflection utility (BeanUtils) to copy the submitted object to the target object, but ignore null values - i.e. fields that are not submitted

引入一个具有所需字段子集的新对象,并使用 BeanUtils.copyProperties(..)将其合并到实体。

Introduce a new object that has the needed subset of fields, and use BeanUtils.copyProperties(..) to merge it to the entity.

替代品?

推荐答案

我发现只要你的网络模型在功能上开始偏离业务层,最好使用视图层对象(模型对象)来收集或显示数据

I've found that as soon as your web model starts to diverge from your business layer in function, it's best to use a view layer object (a model object) to collect, or display the data

实体:

public class com.myapp.domain.UserEntity {

}

模型对象:

public class com.myapp.somesite.web.SomeSiteUserModel {

   public static SomeSiteUserModel from(UserEntity userEntity) {
      ... initialize model ...
   }

   public UserEntity getModelObject() {
      ... get entity back ... 
   }

}

现在所有基于视图的操作都可以将处理交给内部模型对象,如果这是有意义的,否则它可以自己定制它们。当然这个问题是你必须为实体重新编写你想要的所有getter和setter(这是我必须处理的问题,这很烦人),遗憾的是这有点像Java语言问题

now all view based operations can hand off processing to the internal model object if that makes sense, otherwise it can customize them itself. Of course the problem with this is you have to re-write all the getters and setters you want for the entity (an issue that I've had to deal with, that is annoying) unfortunately that is a bit of a Java language issue

这篇关于使用spring mvc提交/绑定部分对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆