Struts2 中的 token 标签有什么用,它是如何工作的?

What is the use of token tag in Struts2 and how does it work?

我发现了这个 <s:token /> 标签,它包含在 JSP 页面的 <s:form></s:form> 标签中。 其他一些 Whosebug link 讨论了它在维护会话和防止重复提交表单方面的用法。这个标签到底有什么用?如果它阻止了双重提交表单,那么当我提交表单时会发生什么,它是如何阻止的?

我在这里回答我自己的问题,因为这可能对将来的人有所帮助,不过我会尝试对此进行更多挖掘并进行更新。

我找到的通俗易懂的英文解释:

"The token tag generates an unique token which is used to find out whether a form has been double submitted. When the form is rendered, a hidden variable is placed as the token value. Let us say, for example that the token is "ABC". When this form is submitted, the Struts Filter checks the token against the token stored in the session. If it matches, it removes the token from the session. Now, if the form is accidentally resubmitted (either by refreshing or by hitting the browser back button), the form will be resubmitted with "ABC" as the token. In this case, the filter checks the token against the token stored in the session again. But because the token "ABC" has been removed from the session, it will not match and the Struts filter will reject the request." (Source)

然而,这两个 Whosebug 答案增加了更多知识。

  • Difference between Token Interceptor and Token Session Interceptor?

  • How to avoid inserting two same records twice when double-clicking the submit button?

<s:token/> 标签的用途:

Stop double-submission of forms.

The token tag is used to help with the "double click" submission problem. It is needed if you are using the TokenInterceptor or the TokenSessionInterceptor. The s:token tag merely places a hidden element that contains the unique token.

(来源:https://struts.apache.org/docs/token.html

What is the use of token tag in Struts2?

example

How it works?

它主要通过使用 class、Helper class 和配置 xml 文件来工作: Token.java , TokenHelper.java, struts-token.xml.