【发布时间】:2023-04-04 03:57:02
【问题描述】:
我在使用 @RequestParam 到 Spring MVC 的具有多个属性的 angular 2 http post JSON 时遇到问题,但它无法绑定到我的对象,我尝试四处搜索,发现还有另一种使用 @ModelAttribute 但仍然得到的方法同样的结果。以下是我的示例代码:
Angular 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 中的对象,但它显示为 null。 下面是我的弹簧控制器:
@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);
}
}
更新: Leon 建议使用对象包装器与 JSON 进行映射的替代方法。我将它作为我的第二个选项,但我的目标是使用 Spring 注释仅将“测试”属性映射到我的 Mdc_CodeType 对象,这可能吗?
【问题讨论】:
标签: json spring spring-mvc angular