I have a form that is submitting to a servlet and processed with the doPost() method. Once the form is submitted, the user is taken to another page with a "Back" button (not the browser's back button). If the Back button is clicked, the form should repopulate with the original input. How can I accomplish this?
If you use javascript:history.back() your browser should automatically take care of that for you.
It is your responsibility to keep the information and repopulate the form manually. You can do this in one of two ways:
- Either you push the content to the client and read it back in when necessary.
- Or you can save the form data for that client in the server space.
I prefer the later by creating a model which represents the form data. When the form is processed, you can save a copy for that client. If the page is reloaded, you can check for the existence of a previous model. If it exists you use that data to populate your form. If it does not exist, you can use a default model or empty values.
There are other advantages of gathering your content into a model which will benefit you later on. For example, if one makes changes to a form and you have an 'Undo' button near the 'Submit' and 'Clear' buttons, you can easily revert to the last known state. In order to active the 'Undo' button you can easily do:
boolean isDirty = savedModel.equals(currentModel);
And enable/disable the 'Undo' button using the boolean rather than having tons of 'if/else' statements to see if a value was changed. Much cleaner.
Jeach!
You'll have to keep up with the data the user submitted in the form.
You could put that data on the in a url, on the request or in the session.
Make sure you escape any unsafe characters when putting them back into the form.
There are a lot of web frameworks out there that make this sort of thing easier to do.
After original form is submitted you have several server-side options:
- keep form values in session and populate them with the form called from 'Back' action;
- add form values as parameters to 'Back' action url so they will be part of the request.
If the user submits the form, is the data put into a database? If so, simply query the database and repopulate the form... If not, consider saving the data to a database.