Home > Back-end >  best way to import form data from HTML to java Spring controller as JSON request body
best way to import form data from HTML to java Spring controller as JSON request body

Time:10-08

I am building my first spring boot project with java in intellij. When capturing form data from an HTML page, is there a 'best practice' way of transporting the data to the server controller as a JSON request body? I've seen solutions with javascript / ajax, but I prefer something more native to the spring library.

CodePudding user response:

There are two ways.

  1. Setting your Back-End as a REST API and completely separate your Front-End and communicating through REST calls. (as you said with JS/Ajax)

  2. Setting your complete app under one roof. Spring and Thymeleaf are a good option. It works like this, every time you do a /GET request then spring will provide a template. Which is a Thymeleaf HTML document which has Thymeleaf specific syntax to make your life easier. You can submit your data to your back-end through forms. When you submit the form then your app decides what happens next, will you be redirected somewhere else or will another template be opened...That's your call.

If you want a quick way to do it, go with the second way. Personally, I like the first one. It separates the concerns perfectly.

  • Related