hellzone
hellzone

Reputation: 5236

How to redirect from spring controller?

I have a MainRedirectController and all requests and responses will redirect from this controller. How can I send request parameter from mainRedirect method to page1 method and send response parameter from page1 method to mainRedirect method?

public class MainRedirectController{

  public ModelAndView mainRedirect(HttpServletRequest request, HttpServletResponse response) {
    String page = ServletRequestUtils.getStringParameter(request, "page", null);
    if(page.equals("page1")){
       //redirect request to page1 controller and 
       //return reponse coming from page1 controller
    }else if(....){
       ...
    }

  }
}


public class Page1Controller{

  public ModelAndView page1(HttpServletRequest request, HttpServletResponse response) {
     response.getOutputStream().print("{\"completed\": \"1\"}");
     response.getOutputStream().flush();
     return null;
  }
}

Upvotes: 1

Views: 2006

Answers (1)

dvelopp
dvelopp

Reputation: 4295

You need to return "redirect:" view to that page. Just use it as constructor parameter:

if(page.equals("page1")){
   return new ModelAndView("redirect:/page1MappingValue")
}

page1MappingValue here is the address to your page1 depending on the mapping.

You can read more about redirects here:

http://www.baeldung.com/spring-redirect-and-forward

Also if you need to get a response just inside the method and you don't need return it directly, you can use RestTemplate-s:

https://spring.io/guides/gs/consuming-rest/

It will allow you to get a response and use it on the back-end inside your logic.

Upvotes: 2

Related Questions