gpt4 book ai didi

Spring MVC : Redirecting from a base controller - How to get the path to redirect to?

转载 作者:行者123 更新时间:2023-12-03 12:18:22 25 4
gpt4 key购买 nike

我已经搜索了又搜索,但没有发现任何说明这是不可能的,也没有任何解释如何做到这一点的内容。

如果您有一个扩展的基本 Controller ,我知道请求映射方法也是继承的。

所以与....

public abstract class BaseController
{

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

......像这样的 Controller ......
@Controller
@RequestMapping("/admin/")
public abstract class AdminController
{
....
}

...将继承一个监听/admin/hello 的方法,该方法返回 hello-view。

这一切都很好。

但是如果我有一个重定向的 BaseController 方法:
public abstract class BaseController
{

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

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

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

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

这可能吗?

最佳答案

一种选择:

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

这是管理 Controller 。
@Controller
@RequestMapping(AdminController.context)
public abstract class AdminController
{
static final String context = "/admin/";
@Override
protected String getControllerContext() {
return context;
}
....
}

另一个涉及反射的选项可能有效......:
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;
}
}

关于Spring MVC : Redirecting from a base controller - How to get the path to redirect to?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15506045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com