Reputation: 647
Following is a code snippet where we can use @ModelAttribute at method parameter level
@ReqestMapping(value = useruri)
public void submitInfo(@ModelAttribute User user) {
// Business logic
}
@ReqestMapping(value = personuri)
public void submitInfo(@ModelAttribute Person person) {
// Business logic
}
Can we do like following?
@RequestMapping(value = genericuri)
public void submitInfo(HttpServletRequest request, @PathVariable String type) {
if (type.equals("user")) {
User user = someSpringMvcMethod(request, User.class)
} else if (type.equals("person")) {
Person person = someSpringMvcMethod(request, Person.class)
}
//Business logic
}
Reason is, I am expecting different type of submitted data based on a type and I want to write a generic controller since only difference is conversion of request data to specific java class. User and Person class has lot of different data and I don't think I can use inheritance/polymorphism to solve my use-case here
Upvotes: 0
Views: 88
Reputation: 21172
I don't recommend such a thing.
Look here
if (type.equals("user")) {
User user = someSpringMvcMethod(request, User.class)
} else if (type.equals("person")) {
Person person = someSpringMvcMethod(request, Person.class)
}
This is already wrong, imho. A single method managing multiple models.
What if you need another model's type? Another if
branch.
For example, this is a lot better
@ReqestMapping("base-path/user")
public void submitInfo(@ModelAttribute final User user) {
commonLogic(user.valueOne, user.valueTwo);
}
@ReqestMapping("base-path/person")
public void submitInfo(@ModelAttribute final Person person) {
commonLogic(person.valueOne, person.valueTwo);
}
private void commonLogic(final String one, final String two) {
... // Business logic
}
commonLogic
manages the common business logic between the models' types.
It centralizes the work.
You can even place commonLogic
in a Service, which is where it should go anyway.
Upvotes: 1