On Tue, 7 Aug 2001, Tom Tibbetts wrote:
> Hi all. Is there example code about how to implement saveToken and
> isValidToken methods. Core J2ee patterns gives a good talk on theory but
> they drop the ball with examples.
The book even quotes the Struts code that implements this pattern :-).
> Thanks in advance. Tom
>
>
This feature is actually used in the example application shipped with
Struts -- but it's so easy to utilize that it's almost invisible.
Down near the bottom of EditRegistrationAction, you will see the call:
saveToken(request);
which tells Struts to invoke the transaction control mechanism. When
registration.jsp is displayed, the <html:form> tag will include an extra
hidden variable with the submit (you can see it with "View Source") that
is then validated by this code in SaveRegistrationAction:
if (!isTokenValid(request)) {
... handle the error ...
}
resetToken(request);
Note that there are *zero* changes necessary in the JSP page itself to use
this stuff -- it's totally a decision of the business logic designer when
transaction tokens are appropriate. (Custom tags are your friend ;-).
The whole point of the exercise is to catch "double posts" to the database
caused by the user using their back button. To prove that it works, try
this:
* Log on to the example app and select the
"Edit your registration" link.
* Make some changes and press Save.
* Although you're now on the main menu again,
use your browser's back arrow and resubmit
the form again.
* You will get an error message because the
transaction control token will no longer
be valid.
As a general design note, this pattern is especially easy to use when you
have a "pre-form" action to set things up (EditRegistrationAction in this
case) and a "post-form" action to process it. The "pre-form" action is
also a perfect place to pre-initialize the form bean with values from your
database.
Craig