Thymeleaf中th:action和th:formaction之间的工作差异

Sum*_*osh 0 spring thymeleaf spring-boot

我是Thymeleaf的新手,我有一个Spring-Boot应用程序,该应用程序在视图页面中使用了Thymeleaf组件。

  <form action="#" th:action="@{/saveStudent}" th:object="${user}" method="post">
    <table>
      <tr> 
        <td>Enter Your name</td>
        <td><input type="text"  th:field="*{userName}"/></td>
        <td><input type="submit" value="Submit"/></td>
      </tr>
   </table>
 </form>
Run Code Online (Sandbox Code Playgroud)

上面的代码对我来说很好用

现在,在使用eclipse代码辅助时,我遇到了几个百里香标签/属性th:form,th:formaction

一旦我将上面的代码更改为以下格式:

<th:form  th:formaction="@{/saveStudent}" th:object="${user}" method="post">
  <table>
    <tr> 
      <td>Enter Your name</td>
      <td><input type="text"  th:field="*{userName}"/></td>
      <td><input type="submit" value="Submit"/></td>
    </tr>
  </table>
</th:form>
Run Code Online (Sandbox Code Playgroud)

它停止工作。我的网页没有提交到服务器。因此,我想了解以下内容:

th:form标签的用途是什么?th:action和th:formaction标签之间有什么区别?

Dar*_*ice 5

“ th:action”和“ th:formaction”标签将创建html标签actionformaction。这个问题与Thymeleaf无关,而是html标签本身。

action标签可以被放置在一个形式,以指定的URL的形式传递给。在您的第一个示例中,提交表单将向发送POST请求/saveStudent

第二个示例是无效的HTML,这就是表单无法提交的原因。formaction可用于覆盖action表单内的表单属性。可以在input标签上使用:

<form th:action="@{/saveStudent}" th:object="${user}" method="post">
  <table>
    <tr> 
      <td>Enter Your name</td>
      <td><input type="text"  th:field="*{userName}"/></td>
      <td><input type="submit" value="Submit"/></td>
      <td><input th:formaction="@{/saveSomewhereElse}" type="submit" value="Submit to other url"/></td>
    </tr>
  </table>
</form>
Run Code Online (Sandbox Code Playgroud)

在此示例中,默认设置action为“提交到”,/saveStudent但是如果有人单击第二个“提交”按钮,则表单将提交到/saveSomewhereElse

通常,action在99%的情况下,您可能只需要标签。