0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

ok thank you. I understand that if-else approach is bad. Another option was, I could replace it with a hashmap of type and corresponding class. But primarily I wanted to see if there is any alternative for annotation available inside method. But thanks a lot for your suggestion. I will mostly go with above common method approach.
@mihirS With the HashMap approach you'd have to maintain an hardcoded initialization anyway. I'd say, place the common business logic in a Service, and autowire the Service in the Controller. That's the most clean solution (and what I do usually myself).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.