Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC GET/redirect/POST

Say I have 2 Spring MVC services:

@RequestMapping(value = "/firstMethod/{param}", method = RequestMethod.GET)
public String firstMethod(@PathVariable String param) {
    // ...
    // somehow add a POST param
    return "redirect:/secondMethod";
}

@RequestMapping(value = "/secondMethod", method = RequestMethod.POST)
public String secondMethod(@RequestParam String param) {
    // ...
    return "mypage";
}

Could redirect the first method call to second(POST) method? Using second method as GET or using session is undesirable.

Thanks for your responses!

like image 315
Nailgun Avatar asked Dec 05 '12 11:12

Nailgun


People also ask

How use redirect attribute in Spring MVC?

You can use RedirectAttributes to store flash attributes and they will be automatically propagated to the "output" FlashMap of the current request. A RedirectAttributes model is empty when the method is called and is never used unless the method returns a redirect view name or a RedirectView.

What is the difference between forward and redirect in Spring MVC?

Forward: is faster, the client browser is not involved, the browser displays the original URL, the request is transfered do the forwarded URL. Redirect: is slower, the client browser is involved, the browser displays the redirected URL, it creates a new request to the redirected URL.

What is RedirectView?

public class RedirectView extends AbstractUrlBasedView implements SmartView. View that redirects to an absolute, context relative, or current request relative URL. The URL may be a URI template in which case the URI template variables will be replaced with values available in the model.

How do I forward a Spring MVC request?

A request can be basically processed in three ways: a) resolved by Spring in a controller action, b) forwarded to a different controller action, c) redirected to client to fetch another URL. Forward: performed internally by Spring. the browser is completely unaware of forward, so its original URL remains intact.


1 Answers

You should not redirect a HTTP GET to a HTTP POST. HTTP GET and HTTP POST are two different things. They are expected to behave very differently (GET is safe, idempotent and cacheable. POST is idempotent). For more see for example HTTP GET and POST semantics and limitations or http://www.w3schools.com/tags/ref_httpmethods.asp.

What you can do is this: annotate secondMethod also with RequestMethod.GET. Then you should be able to make the desired redirect.

@RequestMapping(value = "/secondMethod", method = {RequestMethod.GET, RequestMethod.POST})
public String secondMethod(@RequestParam String param) {
...
}

But be aware that secondMethod can then be called through HTTP GET requests.

like image 118
nanoquack Avatar answered Sep 28 '22 02:09

nanoquack