Spring无法将MultiValueMap映射到bean

时间:2017-07-17 19:53:05

标签: java spring spring-mvc spring-boot

将x-www-form-urlencode数据发布到Spring。 这有效:

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

另一方面,这是一个例外:

  

内容类型'application / x-www-form-urlencoded; charset = UTF-8'不是   支持的

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

这会导致bean上的所有字段都为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;
}

表格数据:

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>

1 个答案:

答案 0 :(得分:2)

我在这里看到两个问题。

  1. 使用@RequestBody注释。它,或者更准确地说它的处理程序 - HttpMessageConverter的子类,无法处理这些情况。您应该处理@ModelAttribute而不是。

  2. 没有二传手。 Spring无法将没有setter的值设置为目标实例。我不知道是否有一个属性直接用字段操作,但我建议避免这样做。制作字段private