@ModelAttribute has no value when using with @RequestParam

1.3k views Asked by At

I have a controller class which has below mapping and I'm trying to call this with ajax.

@RequestMapping(value = "/jobs", method = RequestMethod.POST, headers = "Accept=*/*")
@ResponseBody
public String associate(@ModelAttribute ("job") Job job, @RequestParam(value="ips") String[] ips) {
    logger.debug("associate: No of IP Ranges: {} ", ips.length);
    logger.debug("associate: jobSchedule:  {} " , job.getScanId());
}

Jquery Ajax call as below:

$.ajax({
    type: 'POST',
    url: urlstr,
    data : {job:job ,ips: ipIds.toString()}
    success: function(data, textStatus, jqXHR) {
        if(data != ""){
            if(data != ""){
                alert(data);
                location = ctx + '/rest/settings';
            }
        }
    },
    error: function(jqXHR, textStatus, errorThrown) {
        alert('There was an error in scheduling.' + errorThrown );
    }
}); 

It is able to pring ips length but job.getScanId() returns null. But when I alert in the jsp , it prints the scan ids from my json job object.

I'm not knowing what mistake I'm making. I think I'm right in controller part but I don't know whether I'm passing job object and string array correctly. Any pointers?

1

There are 1 answers

0
Sotirios Delimanolis On

The @ModelAttribute annotation will indicate to Spring to create an instance of the annotated type and populate it (set its fields) using the request parameters in the request. If not parameters match, it won't use any and its fields will remain null.

That's what is going on here. Your client is sending a request parameter

job:job

that I assume does not fit the fields of the Job class. Note that the value you pass to @ModelAttribute, ie. "job" is completely unrelated to the request parameter of the same name.