我需要扩展现有的 Controller 并向其添加一些功能。但是作为一个项目要求,我不能在原始 Controller 中触及,问题是这个 Controller 上有一个 @RequestMapping
注释。所以我的问题是如何向 /someUrl
发出请求到我的新 Controller 而不是旧 Controller 。
这里有一个例子来阐明我在说什么:
原 Controller :
@Controller
public class HelloWorldController {
@RequestMapping("/helloWorld")
public String helloWorld(Model model) {
model.addAttribute("message", "Hello World!");
return "helloWorld";
}
}
新 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";
}
}
如何在不编辑 HelloWorldController
的情况下覆盖原始映射?
最佳答案
作为注释的 Url 映射不能被覆盖。如果两个或多个 Controller 配置了相同的请求 url 和请求方法,您将收到错误。
你可以做的是扩展请求映射:
@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";
}
}
示例:现在如果您调用 yourhost/helloWorld?type=42 MyHelloWorldController
将响应请求
顺便说一句。
Controller 不应是动态内容提供者。您需要一个 @Service
实例。因此,您可以一次实现 Controller 并使用多个 Service 实现。这是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";
}
}
关于java - 如何在另一个 Controller 中覆盖@RequestMapping?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29751416/