Igorovics
Igorovics

Reputation: 416

How to post boolean variable to server side as a field of a ModelAttribute object?

I have a Spring-framework based web application, and I post data from client side to server side as an object using ModelAttribute annotation. I have an Entity bean that contains data (and stored to database later). One of the fields is a boolean field:

@Entity
@Table(name="PLAYER")
public class Player implements Serializable, JSONAble{
...
@Column(name="IS_HUNGARIAN")
private boolean isHungarian
...
}

I send the data to server side with an AJAX call using jQuery:

$.ajax({
   type : "POST",
   url : contextPath + 'saveEditedPlayer',
   data: $('#editPlayerForm').serialize(),
   success : function(result) {
       alert('Success');
   },error:function (xhr, ajaxOptions, thrownError){
   }
});

In the Controller I receive the data like this:

@RequestMapping("/saveEditedPlayer")
@ResponseBody
public String saveEditedPlayer(@ModelAttribute final Player player, @RequestParam(required = false) final String tsiAlso) { 
     final JSONObject result = new JSONObject();
    //some more source code
    return result;
}

All the fields in the Player object are filled fine except the boolean field. According to this link the reason is that boolean values posted to server side as String value, and that is true. I have a workaround solution: I have a String field in the Entity bean, where I can store the boolean data as a String value ("true" or "false"), and in the field's set method I can set the real boolean field's value (thanks to Spring it's done automatically). But I don't think this is the right way to solve this problem.

Is there a way to post my boolean variable without any kind of helper variable? Thank you for any kind of help in advance, if you need some more information, please ask me.

Upvotes: 2

Views: 1601

Answers (1)

Neil McGuigan
Neil McGuigan

Reputation: 48277

You need to name your stuff like this:

Player.java:

...
private boolean hungarian;

public boolean isHungarian() {...}

public void setHungarian(boolean hungarian) {...}
...

Your request variable is then hungarian

Upvotes: 3

Related Questions