2013-12-14 34 views
4

我認爲@RequestBody試圖通過屬性名稱註釋之後將請求params映射到對象。Spring MVC how @RequestBody如何工作

但是,如果我有:

@RequestMapping(value = "/form", method = RequestMethod.GET) 
public @ResponseBody Person formGet(@RequestBody Person p,ModelMap model) { 
    return p; 
} 

請求:

http://localhost:8080/proj/home/form?id=2&name=asd 

返回415

當我改變@RequestBody Person p@RequestParam Map<String, String> params它的確定:

@RequestMapping(value = "/form", method = RequestMethod.GET) 
public @ResponseBody Person formGet(@RequestParam Map<String, String> params) { 
     return new Person(); 
} 

Person類:

public class Person{ 
    private long id; 
    private String name; 

    public Person() { 
    } 

    public Person(long id, String name) { 
     super(); 
     this.id = id; 
     this.name = name; 
    } 
    public long getId() { 
     return id; 
    } 
    public void setId(long id) { 
     this.id = id; 
    } 
    public String getName() { 
     return name; 
    } 
    public void setName(String name) { 
     this.name = name; 
    } 
} 

春vresion 3.2.3.RELEASE

我有什麼錯?

+0

您是否嘗試添加一個默認構造函數到'Person'? – jbx

+0

剛試過,沒有幫助。謝謝。 –

回答

6

不,這是@ModelAttribute的工作,而不是@RequestBody

  • @ModelAttribute填充目標對象的字段與相應的請求參數的值,如果有必要執行轉換。它可以用於由HTML表單生成的請求,與參數的鏈接等。

  • @RequestBody使用預先配置的HttpMessageConverter之一將請求轉換爲對象。它可以用於包含JSON,XML等的請求。但是,沒有HttpMessageConverter複製了@ModelAttribute的行爲。

+0

太好了,謝謝。 –

4

輸入到一個bean需要的轉化:

使用POST或例如用JSON體PUT請求。 這也是很好的「消耗」的請求映射到指定的預期內容TIPE:

@RequestMapping(value = "/form", method = RequestMethod.POST, consumes = "application/json") 

添加實現HttpMessageConverter到servlet上下文轉換的實例(servlet.xml中例如)

<bean id="jsonConverter" 
     class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> 
<property name="supportedMediaTypes" value="application/json" /> 
</bean> 

加入傑克遜的核心和映射器罐類路徑(或pom.xml的)

那麼你可以用它嘗試捲曲

curl -X POST http://localhost:8080/proj/home/form -d '{"name":"asd", "id": 2}' -H 'Content-type:application/json' 

對不起,但我希望它有幫助