Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map Multiple controllers in Spring MVC

I have two controllers in my Application; one is userController, where I have add, delete and update methods; the other one is studentController, where I also have add, delete and update methods.

All the mappings are same in my methods using @RequestMapping annotation in both controllers. I have one confusion: if we are passing the same action from the JSP, then how will the Dispatcher find the corresponding controller? If anybody could describe this using example will be appreciated.

like image 441
AskSharma Avatar asked Sep 28 '13 15:09

AskSharma


People also ask

Can we create multiple controllers in Spring MVC?

In Spring MVC, we can create multiple controllers at a time. It is required to map each controller class with @Controller annotation.

Can 2 controllers have same request mapping?

You cannot. A URL can only be mapped to a single controller. It has to be unique.

How do I connect two controllers in MVC?

You can create a route with same constraints like this: routes. MapRoute(name: "Product", url: "Categories/Product/{id}", defaults: new { controller = "Products", action = "Index", id = UrlParameter. Optional});

How does Spring MVC handle multiple requests?

In Spring, every request is executed in a separate thread. For example, when two users want to log in at the same time, the JVM creates two threads: one thread for the first user and another one for the second user. And these threads work with the singleton bean separately.


1 Answers

You have to set a @RequestMapping annotation at the class level the value of that annotation will be the prefix of all requests coming to that controller,
for example:

you can have a user controller

@Controller
@RequestMapping("user")
public class UserController {

    @RequestMapping("edit")
    public ModelAndView edit(@RequestParam(value = "id", required = false) Long id, Map<String, Object> model) {
        ...
    }
}

and a student controller

@Controller
@RequestMapping("student")
public class StudentController {

    @RequestMapping("edit")
    public ModelAndView edit(@RequestParam(value = "id", required = false) Long id, Map<String, Object> model) {
        ...
    }
}

Both controller have the same method, with same request mapping but you can access them via following uris:

yourserver/user/edit
yourserver/student/edit

hth

like image 101
Frederic Close Avatar answered Oct 15 '22 14:10

Frederic Close