0

I am calling a view of one controller from another controller(say controller1 and controller2 respectively). And it is successfully working, but the browser shows the url of the controller1 even though I redirected to controller2. How to change this?

@Controller

@SessionAttributes

public class UserFormController {

@Autowired
private UserService userService;

@Autowired
private Controller2 controller2;

@RequestMapping(value = "/method1", method = RequestMethod.GET)
public ModelAndView redirectFormPage() {

 return controller2.redirectMethod();

}

here, url "method1" is showing. I want to shows the called url.

Coding world
  • 167
  • 8
  • 23

2 Answers2

0

What does the controller2.redirectMethod() do?

Instead of invoke method directly from the controller use this and put the URL to redirectMethod (redirectURL)

   return new ModelAndView("redirect:/redirectURL");

or

   return "redirect:/redirectURL"

depend on what do you return

In your case, it will treat as normal method.

Controller 1:

@Controller
@RequestMapping("/")
public class Controller11 {     
    @RequestMapping("/method1")
    public String method1(Model model) {
        return "redirect:/method2";
        // If method return ModelAndView
        // return new ModelAndView("redirect:/method2");
    }
}

Controller2:

@Controller
public class Controller22 {
    @RequestMapping("/method2")
    public String method1(Model model) {
        model.addAttribute("method", "method2");
        return "method";
        //If method return ModelAndView
        //  model.addAttribute("method", "method2");        
        //  return new ModelAndView("method");
    }
}

View:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Method1</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p th:text="'Method, ' + ${method} + '!'" />
</body>
</html>
Markovitz
  • 41
  • 3
0

Write another handler in Controller2 which will call redirectMethod().

In Controller2:

@RequestMapping(value = "/redirectFromUser", method = RequestMethod.GET)
public ModelAndView handleRedirectionFromUser() {
    return redirectMethod();
}

And in UserFormController:

@RequestMapping(value = "/method1", method = RequestMethod.GET)
public String redirectFormPage() {
    return "redirect:/url/to/redirectFromUser";
}
Minar Mahmud
  • 2,577
  • 6
  • 20
  • 32