我有一个控制器有4个请求映射,我无法在此控制器中进行更改。是否有可能有一个类(控制器/组件)覆盖其中一个请求映射方法,以使我的自定义实现为此请求映射并使用其他3个请求映射方法。可能吗?
以下是示例代码:
@Controller
public class Base {
@RequestMapping("/add")
public String add() throws Exception {
return "add";
}
@RequestMapping("/update")
public String update() throws Exception {
return "update";
}
@RequestMapping("/remove")
public String remove() throws Exception {
return "remove";
}
@RequestMapping("/show")
public String show() throws Exception {
return "show";
}
}
public class ExtendedBase extends Base {
public String add() throws Exception {
return "newAdd";
}
}
答案 0 :(得分:1)
由于您只想从父控制器覆盖一个方法并保留所有控制器方法的URL,因此您需要一种方法来阻止Spring将URL映射到父控制器,否则您将在添加时获得重复的URL映射儿童控制器。
假设您的控制器是:
package com.theirs.web.controller;
@Controller
@RequestMapping("/base")
public class Base {
@RequestMapping("/add")
public String add() { ... }
@RequestMapping("/update")
public String update() { ... }
@RequestMapping("/remove")
public String remove() { ... }
@RequestMapping("/show")
public String show() { ... }
}
package com.mine.web.controller;
@Controller
@RequestMapping("/base")
public class ExtendedBase extends Base {
@Override
@RequestMapping("/add")
public String add() { ... }
}
您可以在dispatcher-servlet.xml
中尝试此操作:
<context:component-scan base-package="com.theirs.web,com.mine.web">
<context:exclude-filter type="regex" expression="com\.theirs\.web\.controller\.Base" />
</context:component-scan>
这将排除父控制器类被Spring管理,同时允许子类由Spring管理。因此,只有一个类映射到/base
及其子URL。
答案 1 :(得分:0)
仅在您为子控制器提供不同映射的情况下才有可能。否则Spring会抱怨模糊映射(因为你将有两个具有相同映射的控制器)。
解决方案是为您的子控制器设置不同的映射。
@Controller
@RequestMapping(value = "/child")
public class ExtendedBase extends Base {
public String add() throws Exception {
return "newAdd";
}
}
请注意,您应该使用@Controller
注释子类,否则它将无法识别它。
因此,在这种情况下,您可以通过子控制器和父控制器访问add()
。 e.g。
/add
- 会调用Base.add()
/show
- 会调用Base.show()
/child/add
- 会调用ExtendedBase.add()
/child/show
- 会调用Base.show()