2017-03-03 82 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的一部分 –