Vel
Vel

Reputation: 787

How to reuse a model for multiple forms in Spring MVC?

I have below model class

public class User {
private String name;
private String age;
private Address address;
private Contact contact;
// getters and setters
}
class Address {
private String address1;
private String address2;
private String state;
private String city;
// getters and setters
}
class Contact {
private String phone;
private String fax;
// getters and setters
}

I am using this User as model object for multiple forms for different type of users.

  1. Contact is optional or not required for certain user types.
  2. address2 in Address is optional or not required for some user types.

My idea is to have one controller handles this form/page for multiple user types.

Upvotes: 0

Views: 507

Answers (1)

StanislavL
StanislavL

Reputation: 57421

You can use just one form as you need.

Some annotations could be added on fields directly e.g. @NotNull for address1 if it's mandatory for all user types.

The your use class should have marker annotation @Valid to validate Address and Contact

public class User {
    ...
    @Valid
    private Address address;
    @Valid
    private Contact contact;
    ...
}

and you can define Class-level constraints annotation and/or Cross-parameter constraints. (See the example).

So your User class should be annotated with your custom constraint where you can check user type and for each type check whether necessary fields are provided and filled properly.

Upvotes: 1

Related Questions