mR.Angular
mR.Angular

Reputation: 65

Angular 2 http post to Spring MVC (Rest)

I'am having a problem with angular 2 http post JSON with multiple attributes to Spring MVC using @RequestParam but it cannot bind to my object, and i try to search around and found there is another way using @ModelAttribute but still getting the same result. Below is my sample code:

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);

And the JSON is looks like this:

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

Basically I am trying to retrieve "test" and bind to my object in Spring MVC, but it shows null. Below is my spring controller:

@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);
  }
}

Update: There is an alternative method suggested by Leon using object wrapper to map with the JSON. I will take it as my second option, but my objective is mapping only "test" attribute to my Mdc_CodeType object using Spring annotation, is that possible?

Upvotes: 0

Views: 4859

Answers (1)

Leon
Leon

Reputation: 12481

You need to bind the body of the request to a variable using @RequestBody. You need an object to capture the entire body.

@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 is a hypothetical class that encapsulates everything in the request.

Upvotes: 1

Related Questions