Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forward request to another controller in Spring MVC

I'd like to know if there is a way I can forward a request from one controller to another without actually changing the URL in the browser.

@RequestMapping(value= {"/myurl"})
public ModelAndView handleMyURL(){

    if(somecondition == true)
    //forward to another controller but keep the url in the browser as /myurl
}

examples that I found online were redirecting to another url which was causing other controllers to handle that. I don't want to change the URL.

like image 207
sublime Avatar asked Nov 15 '25 09:11

sublime


2 Answers

Try to return a String instead of ModelAndView, and the String being the forward url.

@RequestMapping({"/myurl"})
public String handleMyURL(Model model) {
    if(somecondition == true)
        return "forward:/forwardURL";
}
like image 75
Harshal Patil Avatar answered Nov 17 '25 22:11

Harshal Patil


Instead of forwarding, you may just call the controller method directly after getting a reference to it via autowiring. Controllers are normal spring beans:

@Controller
public class MainController {
  @Autowired OtherController otherController;
  @RequestMapping("/myurl")
  public String handleMyURL(Model model) {
    otherController.doStuff();
    return ...;
  }
}

@Controller
public class OtherController {
  @RequestMapping("/doStuff")
  public String doStuff(Model model) {
    ...
  }
}
like image 37
xtian Avatar answered Nov 17 '25 22:11

xtian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!