如何在另一个控制器中覆盖@RequestMapping? [英] How to override @RequestMapping in another controller?

查看:140
本文介绍了如何在另一个控制器中覆盖@RequestMapping?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要扩展现有的控制器并为其添加一些功能.但是作为项目要求,我无法接触原始控制器,问题是该控制器上有一个 @RequestMapping 批注.因此,我的问题是如何向/someUrl 发出请求,将请求发送到新的控制器,而不是旧的控制器.

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:

原始控制器:

@Controller
public class HelloWorldController {

    @RequestMapping("/helloWorld")
    public String helloWorld(Model model) {
        model.addAttribute("message", "Hello World!");
        return "helloWorld";
    }
}

新控制器:

@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 的情况下覆盖原始映射?

how can I override the original mapping without editing HelloWorldController?

推荐答案

作为注释的网址映射不能被覆盖.如果两个或多个控制器配置了相同的请求url和请求方法,则会出现错误.

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

}

示例:现在,如果您调用 yourhost/helloWorld?type = 42 MyHelloWorldController 将响应请求

Example: Now if you call yourhost/helloWorld?type=42 MyHelloWorldController will response the request

顺便说一句.控制器不应为动态内容提供者.您需要一个 @Service 实例.因此,您可以一次实施Controller并使用多种Service实施.这是 Spring MVC和DI

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

}

这篇关于如何在另一个控制器中覆盖@RequestMapping?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆