如何在 Spring MVC 中映射多个控制器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19068530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 06:15:09  来源:igfitidea点击:

How to map Multiple controllers in Spring MVC

springspring-mvc

提问by AskSharma

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.

我的应用程序中有两个控制器;一个是userController,我有添加、删除和更新方法;另一个是studentController,我也有添加、删除和更新方法。

All the mappings are same in my methods using @RequestMappingannotation 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.

在我的方法中,所有映射都使用@RequestMapping两个控制器中的注释。我有一个困惑:如果我们从 JSP 传递相同的动作,那么 Dispatcher 将如何找到相应的控制器?如果有人可以使用示例来描述这一点,我们将不胜感激。

回答by Frederic Close

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

您必须@RequestMapping在类级别设置一个注解,该注解的值将是进入该控制器的所有请求的前缀,
例如:

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:

两个控制器具有相同的方法,具有相同的请求映射,但您可以通过以下 uri 访问它们:

yourserver/user/edit
yourserver/student/edit

hth

回答by JavaLearner1

We can have any number of controllers, the URL mapping will decide which controller to call..

我们可以有任意数量的控制器,URL 映射将决定调用哪个控制器。

Please refer herefor detailed Spring MVC multiple Controller example

请参阅此处了解详细的 Spring MVC 多控制器示例