2017-03-03 92 views
0

我有一個問題與角2 http發佈JSON與多個屬性到Spring MVC使用@RequestParam但它不能綁定到我的對象,我嘗試搜索周圍,發現還有另一種使用@ModelAttribute的方法,但仍然得到相同的結果。下面是我的示例代碼:Angular 2 http發佈到Spring MVC(休息)

角2(HTTP):

this.http.post('api/codetype-create', JSON.stringify(params), { headers: new Headers({ 'Content-Type': 'application/json' }) }) 
    .toPromise() 
    .then(res => res.json().data) 
    .catch(this.handleError); 

而且JSON是看起來像這樣:

{ 
    "test": { 
    "ctmCode": "11", 
    "ctmMaxLevel": 11, 
    "ctmDesc": "test" 
    }, 
    "test2": { 
    "param1": "abc", 
    "param2": "abc", 
    "param3": "abc" 
    } 
} 

基本上我試圖找回 「測試」 並綁定到我的對象在Spring MVC中,但它顯示爲空。 下面是我的彈簧控制器:

@RestController 
@RequestMapping("/api") 
public class AppController { 
    @Autowired 
    Mdc_CodeTypeService mdcCodeTypeService; 

    @Transactional 
    @RequestMapping(value = {"/codetype-create"}, method = RequestMethod.POST) 
    public ResponseEntity<String> postCreateCodeType(ModelMap model, HttpServletRequest request, 
       @RequestParam(value="test",required=false) Mdc_CodeType test) { 
    try { 
     mdcCodeTypeService.createMdcCodeType(test); 
    } catch (Exception ex) { 
     return new ResponseEntity< String>("failed", HttpStatus.BAD_REQUEST); 
    } 
    return new ResponseEntity<String>("Success", HttpStatus.CREATED); 
    } 
} 

更新: 存在使用對象封裝與JSON映射由Leon建議的替代方法。我將把它作爲第二個選項,但我的目標是使用Spring註釋將「test」屬性映射到我的Mdc_CodeType對象,這可能嗎?

回答

1

您需要使用@RequestBody將請求正文綁定到變量。你需要一個物體來捕捉整個身體。

@RequestMapping(value = {"/codetype-create"}, method = RequestMethod.POST) 
public ResponseEntity<String> postCreateCodeType(ModelMap model, HttpServletRequest request, @RequestBody CompleteRequestBody body) { 
    try { 
    mdcCodeTypeService.createMdcCodeType(body.getTest()); 
    } catch (Exception ex) { 
    return new ResponseEntity< String>("failed", HttpStatus.BAD_REQUEST); 
    } 
    return new ResponseEntity<String>("Success", HttpStatus.CREATED); 
} 

CompleteRequestBody是一個假設的類,它封裝了請求中的所有內容。

+0

感謝您的回覆,但是通過這種方法,我可能不得不建立很多類來處理新的發佈數據,或者這是唯一的方法嗎? –

+0

Java是一種強類型語言,我個人建議對每種類型的請求都有一個具體的類;但是,請記住,您仍然可以使用泛型和多態來抽象出很多複雜性。或者,您可以使對象類型爲HashMap並以這種方式訪問​​數據,但是您會丟失對數據的所有編譯檢查 – Leon

+0

感謝您的建議,使用java類來處理此類響應是我的第二選項,但是,我想知道我們如何使用Spring註釋提取JSON的一部分 –