Spring MVC:从基本控制器重定向 - 如何获取重定向到的路径?

n99*_*n99 7 spring spring-mvc

我进行了搜索和搜索,但没有找到任何说不可能的东西,也没有找到解释如何做的事情.

如果您有一个扩展的基本控制器,我理解请求映射方法也是继承的.

所以....

public abstract class BaseController
{

    @RequestMapping(value="hello", method=RequestMethod.GET)
    public String hello(Model model) {
        return "hello-view;
}
Run Code Online (Sandbox Code Playgroud)

......像这样的控制器......

@Controller
@RequestMapping("/admin/")
public abstract class AdminController
{
 ....
}
Run Code Online (Sandbox Code Playgroud)

...将继承侦听/ admin/hello的方法,该方法返回hello-view.

这一切都很好.

但是如果我有一个重定向的BaseController方法怎么办:

public abstract class BaseController
{

    @RequestMapping(value="hello", method=RequestMethod.POST)
    public String hello(Model model) {
        return "redirect:/success/;
}
Run Code Online (Sandbox Code Playgroud)

据我了解,重定向需要相对或绝对URL而不是视图名?

那么我的AdminController如何确保重定向发生在/ admin/success /?

BaseController方法如何获取AdminController上类级别@requestMapping的句柄?

这可能吗?

dig*_*oel 8

一种选择:

public abstract class BaseController
{
    /** get the context for the implementation controller **/
    protected abstract String getControllerContext();

    @RequestMapping(value="hello", method=RequestMethod.GET)
    public String hello(Model model) {
        return "redirect:"+getControllerContext()+"success/";
    }
}
Run Code Online (Sandbox Code Playgroud)

这是管理员控制器.

@Controller
@RequestMapping(AdminController.context)
public abstract class AdminController
{
    static final String context = "/admin/";
    @Override
    protected String getControllerContext() {
        return context;
    }
 ....
}
Run Code Online (Sandbox Code Playgroud)

涉及可能有效的反射的另一种选择......:

public abstract class BaseController
{
    String context = null;

    @RequestMapping(value="hello", method=RequestMethod.GET)
    public String hello(Model model) {
        return "redirect:"+getControllerContext()+"success/";
    }

    // untested code, but should get you started.
    private String getControllerContext() {
        if ( context == null ) {
            Class klass = this.getClass();
            Annotation annotation = klass.getAnnotation(RequestMapping.class);
            if ( annotation != null ) {
                context = annotation.value();
            }
        }
        return context;
    }
}
Run Code Online (Sandbox Code Playgroud)