(Quick Reference)

6.1.11 处理重复的表单提交 - Reference Documentation

Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith

Version: null

6.1.11 处理重复的表单提交

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

<g:form useToken="true" ...>

Then in your controller code you can use the withForm method to handle valid and invalid requests:

withForm {
   // good request
}.invalidToken {
   // bad request
}

If you only provide the 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:

<g:if test="${flash.invalidToken}">
  Don't click the button twice!
</g:if>

The withForm tag makes use of the session and hence requires session affinity or clustered sessions if used in a cluster.

Grails内置了对表单重复提交的处理,其使用的模式是“同步标志模式(Synchronizer Token Pattern)”。作为开始,你需要先在form标签中定义一个标志:

<g:form useToken="true" ...>

然后在你的控制器代码中使用withForm方法来处理那些有效和无效的请求:

withForm {
   // good request
}.invalidToken {
   // bad request
}

如果你只是使用withForm方法而没有连到invalidToken方法的话,Grails将缺省地存储无效的标志到flash.invalidToken变量中,并且将请求重定向到上一个原始页面。这样就可以在视图中检查了:

<g:if test="${flash.invalidToken}">
  Don't click the button twice!
</g:if>

withForm标签使用的是session,因此要求是兼容会话的或者支持集群的会话-如果在集群中使用的话。