How to post HTML form data to a service method using REST API?

Hi,

I have an HTML form that contains more than 50 fields and I wish to post the fields values of this form into a service method for further processing but I am not quite sure about how to create the REST API endpoint method that will receive the form’s data:

In the existing legacy application the html form posts the data using the following snippet:

"form":{
"attributes":{
    "action":"http://satcom.test/getvesselInfo",
    "method":"post"
},
"buttons":{
    "submit":{
        "title": "Send Form Data",
        "click": function() {
            var val = this.getValue();
            if (this.isValid(true)) {
                alert("Valid value: " + JSON.stringify(val, null, "  "));
                this.ajaxSubmit().done(function() {
                    alert("Posted!");
                });
            } else {
                alert("Invalid value: " + JSON.stringify(val, null, "  "));
            }
        }
    }
}

In the existing ASP.NET MVC application, a controller method like the following one was responsible to handle the request:

[HttpPost]
public ActionResult getvesselInfo(FormCollection collection)
{
     //Store form data into database
     ....
}

Based on the above, I would like to ask you about how a service method in CUBA platform should be built in order to accept the data posted by the form above in order to do further processing.

Thank you

Hi,
I don’t think that you should use standard REST API for middleware service here. You can create a
standard Spring MVC controller that handles your form submit. If you don’t need an authentication you can do the following:

  1. Specify a component-scan package in the web-dispatcher-spring.xml of your project. It is the package where your MVC controller will be scanned. See the documentation for dispatcher-spring.xml.
  2. Create a MVC controller. There a lot of examples in the internet how to handle form submit using Spring MVC. One version of the controller may be:
@RestController
public class MyController {
    @PostMapping("/form")
    public String handleFormSubmit(@RequestBody MultiValueMap<String, String> formParams) {
        return "ok";
    }
}

The URL for this controller method will be: http://localhost:8080/app/dispatch/form
The formParams map will contain form field values.

Thank you very much! This is what I really needed!

Why can’t we use standard REST API for middleware service??

Hi!

You can use generic API and publish your service using CUBA’s XML configuration, it will work like a charm.

For complex cases we’d recommend implementing your own REST endpoints, it’s just more flexible and allows you to reflect your business domain functionality, use better names for resource paths, specify exact HTTP methods for each endpoint, etc.

So, it’s up to you which approach you choose.