Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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

>Solution :

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 redirect by returning a string

To trigger the redirect, 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";
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading