简体   繁体   中英

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.

  • How to use this model to handle above mentioned scenarios?
  • How to write a validator for this model?

You can use just one form as you need.

Some annotations could be added on fields directly eg @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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM