Skip to content
Advertisement

Spring Boot. Forward on RestController

I am implementing a mechanism for replacing short links.

I need to forwarded request to another controller. I found examples how to do it in spring on models, but I don’t understand how to do it in RestControllers

Example what i found (use models)

@Controller
public class ShrotLinkForwardController {

   @RequestMapping("/s/*")
   public String myMethod(HttpServletRequest request) {
       return "forward:/difmethod";
   }
}

Or maybe I’m looking in the wrong direction and I need to make a filter?

UPD. I don’t know the final endpoint, it is calculated in the forwarded method. So, i cant autowired other controller

Advertisement

Answer

There are 2 ways to achieve what you want.

1. Call the method on the target controller directly.

Controllers are just normal Spring beans. You can get it via autowire.

@Controller
public class ShrotLinkForwardController {

  @Autowired
  OtherController otherController;

  @RequestMapping("/s/*")
  public String myMethod(Model model) {
    otherController.doStuff();
    return ...;
  }
}

2. Trigger the forward by returning a string

To trigger the forward, try returning a String instead of ModelAndView.

This is the approach you mentioned in your question. Note that the syntax should be forward:/forwardURL. The string after forward: is the URL pointing to another controller, not the method name.

@Controller
public class ShrotLinkForwardController {

  @RequestMapping("/s/*")
  public String myMethod(Model model) {
    return "forward:/forwardURL";
  }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement