Skip to content
Advertisement

Spring Boot thymeleaf bad request 400 instead of showing user error

I am trying to submit a form using post request and first validate inputs.

However when I make bad inputs (for example all empty) instead of showing error I get bad request (400).

For showing error I am using th:if and th:errors tags in HTML.

If I submit all valid inputs, there is no problem.

Controller class:

JavaScript

HTML form:

JavaScript

Model class (Purchase)

JavaScript

How to make showing error using thymeleaf work?

EDIT: I managed to make it work by adding BindingResult parameter to my post method in Controller class and checking if there are any errors. If yes, i return same page the form is on (/new mapping), which is “neworder”.

return “purchaseerror”; might created a bit of confusion.

JavaScript

Advertisement

Answer

I think your problem could be resolved if you use Model as your 2nd parameter in the createPurchase method. Then inside your method you could do something like the following to add messages:

JavaScript

which would kind of result your method as following (please do amend it your discretion — I am only writing for demonstrative purposes):

JavaScript

The added values in the modelAttribute would then be picked by your Thymeleaf implementation from where you could pick the errors (as you would have populated it) and simply base logic upon that.

You can follow example from here for a better understanding. Just remember that you need to add into the Model before you can lay out logic in your thymeleaf based upon that.

I hope my answer resolves your queries. If not, apologies.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement