Java Question

How to override @RequestMapping in another controller?

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
?

dit dit
Answer

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";
    }

}
Comments