简体   繁体   中英

Cannot bind automatically in AJAX post request to a Java object in Spring MVC

I have two issues:

  1. Cannot get my parameters automatically bound into an Java object (they are being posted with jQuery using AJAX)
  2. I am getting a 406 error, I think this means I am not being able to return the JSON object I would like to

I believe the two problem are different, but the solution to both rely in the same part of the code. Could you help me please? Thanks a lot in advance!

Ajax Request

I am trying to post a very simple object, having an email and a name, like this.

var dataObject = {
    name : this.userName,
    email : this.userEmail,
};
this.$.ajax({
    type : "POST",
    url : '/stock-events/register-to-stock',
    contentType: "application/json",
    data : JSON.stringify(dataObject),
    success : function(data) {
        console.info("data");
    },
    dataType : 'json'
});

Spring MCV Controller

    @ResponseBody @RequestMapping(value = "/register-to-stock", method = RequestMethod.POST)
public StockAlarmJsonResponse submitForm(@Valid @RequestBody StockAlarmModel stockAlarm,
        BindingResult result, Model m) {
    System.out.println("hola");
    System.out.println(stockAlarm);
    StockAlarmJsonResponse response = new StockAlarmJsonResponse();
    if (result.hasErrors()) {
        System.out.println(result);
        response.fail();
    }else{
        System.out.println(stockAlarm);
        response.success();
    }
    return response;
}

Model

  public class StockAlarmModel {


@NotNull @Max(100) @Email
private String email;

@Max(100)
private String name;

@Override
public String toString() {
    return "Email: " + email + '\n' + "Name: " + name;
}
}

Error I get in Java (looks like the parameters are not there)

 org.springframework.validation.BeanPropertyBindingResult: 1 errors
 Field error in object 'stockAlarmModel' on field 'email': rejected value [null]; codes   [NotNull.stockAlarmModel.email,NotNull.email,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [stockAlarmModel.email,email]; arguments []; default message [email]]; default message [may not be null]

Error I get in chrome bug (looks that json object is not being returned successfully)

  POST http://localhost:8080/stock-events/register-to-stock 400 (Bad Request) jquery-     1.9.1.js:8526
  send jquery-1.9.1.js:8526
  jQuery.extend.ajax jquery-1.9.1.js:7978
  StockAlarm.registerAlarm StockAlarm.js:131
  (anonymous function) StockAlarm.js:87
 jQuery.event.dispatch jquery-1.9.1.js:3074
elemData.handle

What Chrome Bug Shows for Request

Content Type / Application Json

Request Payload:

{"name":"santiago","email":"santiago@tiendanube.com"}

I'm under the impression that jQuery will serialize this

var dataObject = {
    name : this.userName,
    email : this.userEmail,
};

into json such as

{"name" : "some username", "email" : "some email"}

You'll therefore want Spring to bind a JSON object to your command object. Change your method to

public @ResponseBody StockAlarmJsonResponse submitForm(@Valid @RequestBody StockAlarmModel stockAlarm, BindingResult result, Model m) {

Note the @RequestBody (which can be used with @Valid ). Spring will use an HttpMessageConverter to attempt to deserialize the JSON into an instance of your StockAlarmModel . I'm not sure if the object will be added to the Model directly. You can always add it yourself if you need to.

AFAIK ModelAttribute tries to bind request parameters to the command object. You don't have request parameters in your ajax request.

I don't think your object is being created correctly.

As posted earlier, @RequestBody will attempt to deserialize the JSON object to to the annotated type but you need to have setters in your entity's class. Try adding this to your model:

public class StockAlarmModel {
  .
  .
  .
  public void setName(String name) {
    this.name = name;
  }
  public void setEmail(String email) {
    this.email= email;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM