Reputation: 65
I have 2 controllers involved in a fairly simple flow. One of them does some processing and POSTS to the other which then redirects to a page that renders. The redirect is failing but with no errors. To simplify my use case and identify the issue, I have collapsed it down to these 3 methods -
@RequestMapping(value="/provider/g1", method=RequestMethod.GET)
public void g1(HttpServletRequest request, HttpServletResponse response) {
logger.debug("In g1. posting to pr1");
try {
URI location = restTemplate.postForLocation("http://localhost:8082/provider/pr1", null);
logger.debug("post response=" + location.toString());
} catch (RestClientException re) {
logger.error("Unable to post to pr1.");
}
}
@RequestMapping(value="/provider/pr1", method=RequestMethod.POST)
public void pr1(HttpServletRequest request, HttpServletResponse response) {
logger.debug("In pr1. sending redirect to rd1");
// return "redirect:/provider/rd1";
try {
String rd1Path = "http://localhost:8082/provider/rd1";
response.sendRedirect(response.encodeRedirectURL(rd1Path));
} catch (IOException e) {
logger.error("Error redirecting to rd1");
e.printStackTrace();
}
}
@RequestMapping(value="/provider/rd1", method=RequestMethod.GET)
public void rd1(HttpServletRequest request, HttpServletResponse response) {
logger.debug("In rd1");
}
I have tried both the relative path and the fully qualified path and its the same result.
The output is -
In g1. posting to pr1.
In pr1. sending redirect to rd1
post response=http://localhost:8082/provider/rd1
I would like to know what I am doing wrong and how I can make this work.
Thank you,
SR
Upvotes: 1
Views: 1743
Reputation: 7568
why dont you just do :
@RequestMapping(value="/provider/pr1", method=RequestMethod.POST)
public String pr1() {
logger.debug("In pr1. sending redirect to rd1");
return "redirect:/provider/rd1";
}
Upvotes: 0
Reputation: 279940
Read the javadoc of RestTemplate#postForLocation(..)
. It states
Create a new resource by POSTing the given object to the URI template, and returns the value of the Location header.
Remember that POST-REDIRECT-GET is a very common pattern in web applications.
So you make an HTTP POST request to http://localhost:8082/provider/pr1
which returns a 302 response with a Location
header set to http://localhost:8082/provider/rd1
, which is what is printed.
Your rd1
is never invoked because no request is ever sent that matches its mapping.
You might be looking to use another postXxx
method of RestTemplate
.
Upvotes: 2