How to implement a POST-REDIRECT-GET in Play Framework
Asked Answered
O

2

6

Let's say I have two controller methods: Users.preInsert and Users.insert. The preInsert method is the one used to display the user entry form (GET), while the insert method is responsible for the actual insertion (POST) or calling the 'insert' service. This is how the routes looks like:

GET    /users/add                           controllers.Users.preInsert(...)
POST    /users/add                           controllers.Users.insert(...)

So how do I redirect a request (POST to GET) without losing the parameters like error messages returned from the insert service and the values inputed by the client so that they can be accessed and displayed in the entry form. The parameters may involve some complex objects. I have implemented it using the Caching API but I would like to know if there are any better ways of doing it.

Observable answered 14/9, 2013 at 11:5 Comment(3)
You should use sessions rather than caching.Stupid
@LorenzMeyer you can only store string values in sessionsObservable
Sorry, I thought in PHP not Java. But can't you serialize your data ?Stupid
M
3

That's the exact purpose of the Form objects (http://www.playframework.com/documentation/2.1.1/ScalaForms).

And I think there is a an error in your routes, it could look like:

GET    /users/add                           controllers.Users.preInsert(...)
POST   /users/add                           controllers.Users.insert(...)

You should definitively take a look at the form sample.

Many answered 14/9, 2013 at 12:36 Comment(2)
Thanks for pointing out the mistake. I'ts now fixed. About the forms, yes I have also used them together with the Cache API.Observable
and also, thanks for the example (I didn't see the last link the first time I read your answer). Now every thing works fine.Observable
K
0

You don't need to redirect it back to the preInsert action, instead at the beginning of the insert check if form has errors and it it has display your view containing form (the same which you used in preInsert). It's described in the doc mentioned by nico_ekito in section Handling binding failure

Kamkama answered 14/9, 2013 at 16:46 Comment(2)
...but if I click the refresh button, a form resubmission dialog would appear because it was a post requestObservable
...but any HTML form is NOT a subject to refresh - if user will refresh the view it will display the GET route with preInsert action and blank form - and that's quite obvious behavior.Kamkama

© 2022 - 2024 — McMap. All rights reserved.