Jason Chan
Jason Chan

Reputation: 389

Spring controller disable parameters from body

I have a spring endpoint that looks like this:

    @PostMapping(path = "/test",
        consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE},
        produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseStatus(HttpStatus.OK)
public TestDTO test(TestDTO testDTO){
    return testDTO;
}

with the DTO looking like this:

public class TestDTO {

    @ApiModelProperty(
            name = "sample",
            value = "sample",
            dataType = "String",
            example = "shhhhhh"
    )
    private String sample;

}

so obviously, a curl request like this:

curl --location --request POST 'localhost:8081/test' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'sample=testReturnData'

returns

{
    "sample": "testReturnData"
}

But, if I add a parameter like this

curl --location --request POST 'localhost:8081/test?sample=doNotIncludeThis' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'sample=testReturnData'

I get a response back like this:

{
    "sample": "doNotIncludeThis,testReturnData"
}

I only want spring to grab data from the body, not the param. I want the response to look like

{
    "sample": "testReturnData"
}

The @RequestBody annotation does not work with x-www-form-url-encoded format (which is the format I need), because it will return a 415.

Upvotes: 1

Views: 463

Answers (1)

tbatch
tbatch

Reputation: 1849

I think you are looking for the wrong solution. Why do you get a 415 when you use @RequestBody? This is not standard behavior.

You see, Spring doesn't recognize the body of a request when application/x-www-form-urlencoded is used. The Spring documentation states:

The spring-web module provides FormContentFilter to intercept HTTP PUT, PATCH, and DELETE requests with a content type of application/x-www-form-urlencoded, read the form data from the body of the request, and wrap the ServletRequest to make the form data available through the ServletRequest.getParameter*() family of methods.

In order to configure Spring properly, you need to configure Spring's FormContentFilter. This should be enabled by default, but you can make sure it is by setting it in the application.properties.

spring.mvc.formcontent.putfilter.enabled=true

Upvotes: 1

Related Questions