Reputation: 4161
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.
Upvotes: 4
Views: 23320
Reputation: 3169
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) {
...
}
}
Upvotes: 3
Reputation: 6759
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";
}
Upvotes: 7
Reputation: 933
As far as I know "forward" of a request will be done internally by the servlet, so there will not be a second request and hence the URL should remain the same. Try using the following code.
@RequestMapping(value= {"/myurl"})
public ModelAndView handleMyURL(){
if(somecondition == true){
return new ModelAndView("forward:/targetURL");
}
}
Upvotes: 3