0

I have an class that contains an Boolean attribute

class A {
    Boolean marked;

    [here getter and setter]
}

On my jsp page I connect the checkbox to the model attribute:

<form:form method="POST" action="updateA" modelAttribute="myAInstance">
    <form:checkbox path="marked"/>Valid<br>
    <input type="submit" value="Save"/>                             
</form:form>    

...

<span>From the DB: ${myAInstanceFromDB} </span>  // this displayes true

When submitting the Controller gets the correct value (myAInstance) and I save it in the DB. But if I reload the page (myAInstanceFromDB) the checkbox I have previously selected and saved is not checked. I guess it's beause the path of the checkbox points to modellattribute to be post to the server and not to the database object I past to the page. How do I mark the checkbox when loading the page?

Sangram Badi
  • 4,054
  • 9
  • 45
  • 78
Otis Ottington
  • 425
  • 5
  • 17
  • what is the value you are saving in DB? – Jobin Nov 07 '16 at 09:22
  • I use MySQL and hibernate. The property in the java class is Boolean and the DB-column is of type bit(1). Using MySQL Workbench I see a 1 (for true) when I execute a select. – Otis Ottington Nov 07 '16 at 09:29
  • Here are some of the answers: http://stackoverflow.com/questions/7845741/setting-jsp-checkbox-with-a-value-from-database http://stackoverflow.com/questions/5052003/how-to-set-checked-checkbox-based-on-database-record – KayV Nov 07 '16 at 10:06

1 Answers1

0

You can use the following

<input type="checkbox" name="myVal" id="myVal" value="checkVal" <%= ("true".equals(myAInstanceFromDB) ? "checked" : "") %>>

Another way is:

<input type="checkbox" name="myVal" id="myVal" value="checkVal" ${myAInstanceFromDB == 'Head' ? 'checked' : ''}>
KayV
  • 12,987
  • 11
  • 98
  • 148
  • Do I have to use that standard input type checkbox? I am using spring so I have <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> . It does not have a checked attribute. But it has a path, which makes it very comfortable to pass attributes inside a model. – Otis Ottington Nov 07 '16 at 10:31