Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring boot Rest controller - convert form-encoded body to POJO

I would like to process an HTTP POST request hitting my rest endpoint and convert its body to my defined POJO. I was successful in the past with mapping between JSON and POJOs but I am struggling with this form encoded content.

I have a controller as follows:

@Slf4j
@RestController("/example")
public class GatewayController {

    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public void describeInstances(@RequestBody MyPojo body) {

        log.debug("Value1: " + body.getValue1());

    }

}

And a POJO:

@Data
public class MyPojo {

 private String value1;
 private String value2;
 ...
}

I am hitting the controller with a POST request which looks as follows:

Content-Type: application/x-www-form-urlencoded
Body: value1=abc&value2=efg...

But all I am getting is 415 Unsupported Media Type. Any help is appreciated.

EDIT: when I change the POJO into String and just print the body, it works (without receving the unsupported media type exception) so it is definitely in the POJO declaration.

Follow up:

Is it possible to annotate the POJO attributes to allow different names of the fields (to avoid using undorscope inside variable names, for example)?

Something like:

@Attribute("value_name")
private String valName;
like image 698
Smajl Avatar asked Oct 28 '25 20:10

Smajl


1 Answers

@ModelAttribute is the recommended way to get form data in your controller. e.g.

public void describeInstances(@ModelAttribute("mypojo") MyPojo body)

and

@Data
@ModelAttribute("mypojo")
public class MyPojo {

Read the spring docs for more info here

like image 193
Manos Nikolaidis Avatar answered Oct 31 '25 09:10

Manos Nikolaidis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!