////
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
////

Grails has built-in support for handling duplicate form submissions using the "Synchronizer Token Pattern". To get started you define a token on the link:{gspTagsRef}form.html[form] tag:

[source,xml]
----
<g:form useToken="true" ...>
----

Then in your controller code you can use the link:{controllersRef}withForm.html[withForm] method to handle valid and invalid requests:

[source,groovy]
----
withForm {
   // good request
}.invalidToken {
   // bad request
}
----

If you only provide the link:{controllersRef}withForm.html[withForm] method and not the chained `invalidToken` method then by default Grails will store the invalid token in a `flash.invalidToken` variable and redirect the request back to the original page. This can then be checked in the view:

[source,xml]
----
<g:if test="${flash.invalidToken}">
  Don't click the button twice!
</g:if>
----

Tokens are single-use. When `withForm` validates a token, Grails consumes that token atomically, so duplicate concurrent submissions for the same token allow exactly one request to run the valid block and route the rest to `invalidToken`. Token state is stored in the session and bounded to 100 form URL buckets, with at most 100 tokens per URL. If either limit is exceeded, Grails drops the oldest URL bucket or oldest token for that URL. Applications that keep many unsubmitted forms open in one session can therefore expire the oldest tokens and receive `invalidToken` when those forms are submitted later.

WARNING: The link:{controllersRef}withForm.html[withForm] tag makes use of the link:{controllersRef}session.html[session] and hence requires session affinity or clustered sessions if used in a cluster.
