0

I am trying to forward the request to another url in spring boot.

I know how to forward the request from one endpoint to another endpoint in the same spring boot application. The code for this is like -

@GetMapping("/home")
public ModelAndView home(@PathVariable(name = "env", required = false) String env) {

    return new ModelAndView("index");
}
@GetMapping("/forward")
String callForward(){
    return "forward:/home";
}

Here If I go to http://localhost:8080/forward then it will be server by "/home" endpoint and we'll get the home page rendered. Interesting thing here is "url" in the browser remains same http://localhost:8080/forward.

My requirement is > I want to forward to the request to any third party url for example when http://localhost:8080/forward is called I want it to be served by https://google.com/forward.

How can I do it.

I am open to any solution which can fulfill the requirement.

Arvind Kumar
  • 459
  • 5
  • 21
  • That is called a proxy and is more complex then a simple forward (which is within the same application). – M. Deinum May 22 '20 at 10:10

1 Answers1

0

There is a difference between Forward vs Redirect.

Forward: happens on the server-side, servlet container forwards the same request to the target URL, hence client/browser will not notice the difference.

Redirect: In this case, the server responds with 302 along with new URL in location header and then client makes another request to the given URL. Hence, visible in browser

Regarding your concern, it can be achieved using multiple ways.

Using RedirectView

@GetMapping("/redirect")
RedirectView callRedirect(){
    return new RedirectView("https://www.google.com/redirect");
}

Using ModelAndView with Prefix

@GetMapping("/redirect")
ModelAndView callRedirectWithPrefix(){
    return new ModelAndView("redirect://www.google.com/redirect");
}

Usecase for forwarding could be something like this (i.e. where you want to forward all request from /v1/user to let's /v2/user on the same application)

@GetMapping("/v1/user")
ModelAndView callForward(){
    return new ModelAndView("forward:/v2/user");
}

The second approach (using ModelAndView) is preferable as in this case, your controller will have no change where it redirects or forwards or just returning some page.

Note: As mentioned in comments, if you are looking for proxying request, i would suggest checking this SO Thread

Community
  • 1
  • 1
lucid
  • 2,722
  • 1
  • 12
  • 24
  • the /forward call is not working. throwing 404. And problem with redirect is it changes the url in the browser as well which I want to keep the same. Checking the proxy part – Arvind Kumar May 22 '20 at 14:24
  • @ArvindKumar forward will look for a resource within same server, and as it wouldn't find anything for `yourhost:port/www.google.com/forward`, it will be returning 404. – lucid May 22 '20 at 17:13