Search code examples
javaspringthymeleaf

Thymeleaf href inside form going to different page


I'm trying to implement a cancel button that takes you to the "home" page. However, it tries to submit to the controller defined in the th:action of the form instead of the th:href. Is there way to implement this cancel button without defining a mapping in the controller?

<form th:action="@{/manageUser}" method="post">
  <div>
    <button type="submit">Submit</button>
    <a href="index.html" th:href="@{/}">
      <button name="cancel">Cancel</button>
    </a>
    </span>
  </div>
</form>

I get the following:

There was an unexpected error (type=Bad Request, status=400).
Parameter conditions ... not met for actual request parameters

The th:href works fine if it's outside of the form element


Solution

  • If you insist on using <button> element try this:

    <button type="submit">Submit</button>
    <button type="button">
        <a href="/">Cancel</a>
    </button>
    

    You could also use the <a> element without <button> and style it in CSS if you want:

    <button type="submit">Submit</button>
    <a href="/">Cancel</a>