Spring MVC : Redirecting from a base controller - How to get the path to redirect to?
spring, spring-mvc
Solution
One option:
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/";
}
}
and here's the admin controller.
@Controller
@RequestMapping(AdminController.context)
public abstract class AdminController
{
static final String context = "/admin/";
@Override
protected String getControllerContext() {
return context;
}
....
}
Another option that involves reflection that might work...:
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;
}
}
Problem
I have searched and searched and have not found anything that says this is not possible, nor anything that explains how to do it. If you have a Base Controller that is extended I understand that the request mapped methods are also inherited. So with.... ``` public abstract class BaseController { @RequestMapping(value="hello", method=RequestMethod.GET) public String hello(Model model) { return "hello-view; } ``` ...a Controller like so ... ``` @Controller @RequestMapping("/admin/") public abstract class AdminController { .... } ``` ...will inherit a method listening at /admin/hello that returns the hello-view. This is all fine. But what if I have a BaseController method that redirects: ``` public abstract class BaseController { @RequestMapping(value="hello", method=RequestMethod.POST) public String hello(Model model) { return "redirect:/success/; } ``` As I understand it the redirect requires either a relative or absolute URL rather than a viewname? So how does my AdminController ensure the redirect takes place to /admin/success/? How does the BaseController method get a handle on the class level @requestMapping on my AdminController? Is this possible?