I need to extend an existing controller and add some functionality to it. But as a project requirement I can't touch in the original controller, the problem is that this controller have an @RequestMapping
annotation on it. So my question is how can I make requests to /someUrl
go to my new controller instead of the old one.
here is a example just to clarify what I'm talking about:
Original controller:
@Controller public class HelloWorldController { @RequestMapping("/helloWorld") public String helloWorld(Model model) { model.addAttribute("message", "Hello World!"); return "helloWorld"; } }
new Controller:
@Controller public class MyHelloWorldController { @RequestMapping("/helloWorld") public String helloWorld(Model model) { model.addAttribute("message", "Hello World from my new controller"); // a lot of new logic return "helloWorld"; } }
how can I override the original mapping without editing HelloWorldController
?
Url mapping as annotation can not be overridden. You will get an error if two or more Controllers are configured with the same request url and request method.
A @RequestMapping on the class level is not required. Without it, all paths are simply absolute, and not relative.
In the code snippet above, the method element of the @RequestMapping annotations indicates the HTTP method type of the HTTP request. All the handler methods will handle requests coming to the same URL ( /home), but will depend on the HTTP method being used.
The @RequestMapping annotation can be applied to class-level and/or method-level in a controller. The class-level annotation maps a specific request path or pattern onto a controller. You can then apply additional method-level annotations to make mappings more specific to handler methods.
Url mapping as annotation can not be overridden. You will get an error if two or more Controllers are configured with the same request url and request method.
What you can do is to extend the request mapping:
@Controller public class MyHelloWorldController { @RequestMapping("/helloWorld", params = { "type=42" }) public String helloWorld(Model model) { model.addAttribute("message", "Hello World from my new controller"); return "helloWorld"; } }
Example: Now if you call yourhost/helloWorld?type=42 MyHelloWorldController
will response the request
By the way. Controller should not be a dynamic content provider. You need a @Service
instance. So you can implement Controller once and use multiple Service implementation. This is the main idea of Spring MVC and DI
@Controller public class HelloWorldController { @Autowired private MessageService _messageService; // -> new MessageServiceImpl1() or new MessageServiceImpl2() ... @RequestMapping("/helloWorld") public String helloWorld(Model model) { model.addAttribute("message", messageService.getMessage()); return "helloWorld"; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With