Passing / linking partial objects using spring mvc

Spring MVC's binding mechanism is powerful, but now I am faced with a trivial problem, which I wonder about:

  • User JPA entity, which is also used for binding and verification (i.e. at all levels)
  • The page "Edit profile", which should not change the password or some other properties of the object.

Two ways I can think of:

  • Using the same object

    • use @InitBinder to configure the list of forbidden properties
    • get target user (by id)
    • then use the reflection utility (BeanUtils) to copy the presented object to the target object, but ignore null values ​​- that is, fields that are not sent
  • Introduce a new object that has the required subset of fields, and use BeanUtils.copyProperties(..) to combine it with the entity.

Alternatives?

+4
source share
3 answers

I found that as soon as your web model begins to diverge from your business level in function, it is best to use a presentation-level object (model object) to collect or display data

an object:

 public class com.myapp.domain.UserEntity { } 

model object:

 public class com.myapp.somesite.web.SomeSiteUserModel { public static SomeSiteUserModel from(UserEntity userEntity) { ... initialize model ... } public UserEntity getModelObject() { ... get entity back ... } } 

now all operations based on the view can transfer processing to the internal object of the model, if that makes sense, otherwise it can configure them independently. Of course, the problem is that you have to rewrite all the recipients and setters that you want for the object (the problem I had to deal with is annoying), unfortunately this is a Java language problem

+2
source

I just checked out the last two Spring projects that I have been working on, and in both places the following approach is used:

On the JSP page for the form, the change password field has a name that does not match the name of the password field in the User bean, so it will not be displayed in the bean. Then, in the onSubmit method, there is a separate check to see if a new password has been submitted, and if that were the case, the change was clearly reflected.

Congratulations, Vasil

+1
source

First you can read the object from the database and bind the query. You can find an example in FuWeSta-Sample .

It uses a helper bean that must be initialized by Spring.

0
source

All Articles