2017-07-17 198 views
1

将x-www-form-urlencode数据发布到Spring。 这工作:Spring无法将MultiValueMap映射到bean

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

这在另一方面,给出了一个例外:

内容类型 '应用程序/ x-WWW窗体-urlencoded;字符集= UTF-8' 不 支持

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

,这导致在各个领域的豆被空:

@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> 
+0

我加了答案,你可以查看吗? – Andrew

回答

2

我看到这里有两个问题。

  1. 使用@RequestBody注释。它或者更确切地说它的处理程序 - HttpMessageConverter的子类不能处理这些情况。您应该改用@ModelAttribute

  2. 缺少setters。 Spring不能将没有setter的值设置到目标实例。我不知道是否有财产直接与领域经营,但我会建议避免这种情况。使字段private

+0

试过并没有工作。在Fud private上创建字段并添加getter和setter,将控制器签名更改为'''@RequestMapping(method = RequestMethod.POST,consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) public void sumbitFUD(@ModelAttribute Fud request)''' Fud仍然是空的 – AfterWorkGuinness