How to map Multiple controllers in Spring MVC

前端 未结 2 1795
天涯浪人
天涯浪人 2021-02-04 06:44

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

2条回答
  •  野性不改
    2021-02-04 07:07

    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 model) {
            ...
        }
    }
    

    and a student controller

    @Controller
    @RequestMapping("student")
    public class StudentController {
    
        @RequestMapping("edit")
        public ModelAndView edit(@RequestParam(value = "id", required = false) Long id, Map 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

提交回复
热议问题