kamil
kamil

Reputation: 3522

spring mvc passing objects with post method

I'm trying to pass submited form to my page Controller. I'm constructing JSON object like this:

{
"periodId": "1",
"domainId": "46",
"modelTypeId": "1",
"modelGroup": {
    "modelGroupName": "123",
    "modelGroupDescription": "abc"
}
}

Where I'd like to objects *Id to be passed as Integer and modelGroup as full object. So my goal is somehow make this work:

JS file

jQuery.ajax( "/Models/SaveModel", {
    type:"POST",
    dataType:'json',
    contentType:"application/json",
    data:JSON.stringify( output )
} );

Page Controller

@RequestMapping(value = "/SaveModel", method = RequestMethod.POST, headers = {"content-type=application/json"})
public
@ResponseBody
boolean createModel( SettlementModelGroup modelGroup, 
                     Integer periodId,
                     Integer domainId,
                     Integer modelTypeId )
{
    //process data here
}

Is it possible or do I have to make @RequestBody String object annotation and then parse JSON file?

Upvotes: 2

Views: 5985

Answers (3)

Maximus
Maximus

Reputation: 67

After @RequestBody you must write one object, which contain model class (getters/setters)

Upvotes: 0

Biju Kunjummen
Biju Kunjummen

Reputation: 49935

Spring MVC by default will not do this for you - if you want to use the default approach, you can like you have said create a wrapper type with your modelGroup, periodId, domainId, modelTypeId and annotate the wrapper type with @RequestBody.

If you absolutely want an approach along the lines of what you have written, an approach will be to :

Create a custom annotation - say @JsonArg

Annotate the relevant parameters with this annotation

boolean createModel( @JsonArg SettlementModelGroup modelGroup, 
                     @JsonArg Integer periodId,
                     @JsonArg Integer domainId,
                     @JsonArg Integer modelTypeId );

Write a custom HandlerMethodArgumentResolver which will support @JsonArg annotated arguments:

boolean supportsParameter(MethodParameter parameter){
  return (parameter.getParameterAnnotation(JsonArg.class)!=null);
}

Write logic to parse out the relevant parameter from the request body:

public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

Upvotes: 1

dnc253
dnc253

Reputation: 40347

If you created an object that held all 4 of the objects you list as parameters above, then you could just annotate that one parameter with @RequestBody and it would convert it all for you.

Upvotes: 0

Related Questions