简体   繁体   中英

Spring mvc - Use modelAttribute inside method instead of method argument as annotation

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

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.

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