1

I have a class which has multiple controller in it and from one of the controller i want to call another controller which is in different class and when the particular controller is called that controller will create the view.

my codes are
class one // class from which controller will be called

    @Controller
@RequestMapping(value="/register")
public class PatientController {
@RequestMapping(value="/demo1", method=RequestMethod.GET)
public String demo1(){
    System.out.println("Demo1 method.....");
    return "redirect:user/dashboard";
}
}  

Class second // controller of this class to be called

@Controller
        @RequestMapping("/user")
    public class UserDasboardController {
    @RequestMapping(value="/dashboard", method=RequestMethod.GET)
        public String get(ModelMap model){

            return "userdashboard";// returning view
        }

    }  

after the first controller is called gives url as ".../register/user/dashboard" however it should give url as"..../user/dashboard".

please suggest how can I achieve this. Or there is any other way of doing same thing.

Vipul Singh
  • 393
  • 9
  • 26

2 Answers2

1

when using redirect for the same controller file we can use this as

return "redirect: controllerName"  

if you want to call the controller of another class you have to call it as using / before it so that will be as

"redirect:/firstController/yourSubController"  

Hope this helps.

Code_Singh
  • 48
  • 6
0

Another solution is: MvcUriComponentsBuilder MvcUriComponentsBuilder docs

There are some great methods like: fromMethod(), fromController() and more. You can receive proper redirection path to another method/controller automatically.

Example - redirect to another controller:

final UriComponentsBuilder uriComponents = MvcUriComponentsBuilder.fromController(WheredoYouWantToRedirectController.class);
final String path = uriComponents.build().getPath();

return REDIRECT_PREFIX+path;

In the same way you may work with redirection to methods. MvcUriComponentsBuilder helps to reduce errors connected with redirections.

Please check documentation for more info.

tomaszwasik
  • 119
  • 9