AfterWorkGuinness
AfterWorkGuinness

Reputation: 1850

Spring can't map MultiValueMap to bean

Posting x-www-form-urlencode data to Spring. This works:

@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public void sumbitFUD(@RequestBody final MultiValueMap<String, String> formVars) {
}

This on the other hand, gives an exception:

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported

@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public void sumbitFUD(@RequestBody Fud fud) {
}

And this results in all fields on the bean being null:

@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public void sumbitFUD(Fud fud) {
   //not using @RequestBody 
}

FUD:

public class Fud {

    public String token_id;
    public String team_doamin;
    public String channel_id;
    public String user_id;
    public String user_name;
    public String command;
    public String text;
    public String response;
}

Form data:

token%abc=&team_id%3DT0001=&team_domain%3Dexample=&channel_id%3DC2147483705=&channel_name%3Dtest=&user_id%3DU2147483697=&user_name%3DSteve=&command%3D%2Fweather=&text%3D94070=&response_url%3Dhttps=%2F%2Fhooks.slack.com%2Fcommands%2F1234%2F5678

POM:

<dependencies>
        <dependency>
            <groupId>net.gpedro.integrations.slack</groupId>
            <artifactId>slack-webhook</artifactId>
            <version>1.3.0</version>
        </dependency>
        <!-- Spring Frameworks for Web, MVC and Mongo -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- JUnit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

Upvotes: 1

Views: 1774

Answers (1)

Andrew
Andrew

Reputation: 49656

I see two problems here.

  1. The use of the @RequestBody annotation. It, or more precisely its handler - a subclass of the HttpMessageConverter, can't handle these cases. You should deal with the @ModelAttribute instead.

  2. The absence of setters. Spring can't set values, that come in, to a target instance without setters. I do not know whether there is a property to operate directly with fields, but I would recommend avoiding that. Make the fields private.

Upvotes: 2

Related Questions