Annotation #AssertTrue is not working properly - spring

My poblem is connected with #AssertTrue annotation and some how with Thymeleaf. Actualy I should scheck password for the equality on a registration web page, for this I hava a parameters in my Registrartion Form class, they are Name,password, check_password,check_password_condition, adress. Actually I have made several changes in y code since I have aske my question here. I have used equals() method instead of == and acording this post
Spring validation #AssertTrue
have set a validation property boolean check_password_condition but my code still does not work. This way I use Errors interface to ask my page for validation rules. I think that using of the annotation #AssertTue for my method sould automatically call my method isCheckpassword() from RegistrationForm class and then in #PostMapping method of the Controller asked for the validation rule this.password.equals(this.check_password)
Am I right or not????
#AssertTrue(message = "{RegistrationForm.check_password.AssertTrue}")
public boolean isCheckpassword(){
if(this.password.equals(this.check_password)){
return this.check_password_condition=true;
}
else return this.check_password_condition=false;
}
#PostMapping("/register")
String registerNew(#Valid RegistrationForm form, Errors result) {
if (result.hasErrors()) {
return "register";
}
customerManagement.createCustomer(form);
return "redirect:/";
}
But I get whitepage error when the conditions for the creating new user are not met.
here additionally I provide my Thymeleaf code:
<div class="field">
<label th:text="#{register.check_password}" for="check_password">Repasswort</label>
<input id="check_password" name="check_password" th:field="*{check_password}" th:errorclass="fieldError" type="password"
required="required"/><br/>
<p th:if="${#fields.hasErrors('check_password')}" th:errors="*{check_password}">Das Passwort darf
nicht leer sein.</p>
</div>
This is my Registration From class
class RegistrationForm {
#NotEmpty(message = "{RegistrationForm.name.NotEmpty}") //
private final String name;
#Size(min = 2, max = 14, message = "{RegistrationForm.password.Size}")
#NotEmpty(message = "{RegistrationForm.password.NotEmpty}") //
private final String password;
#NotEmpty(message = "{RegistrationForm.check_password.NotEmpty}") //
private String check_password;
private boolean check_password_condition;
#NotEmpty(message = "{RegistrationForm.address.NotEmpty}") // s
private final String address;
public RegistrationForm(String name, String password,String check_password, String address) {
this.name = name;
this.password = password;
this.check_password=check_password;
this.address = address;
}
#AssertTrue(message = "{RegistrationForm.check_password.AssertTrue}")
public boolean isCheckpassword(){
if(this.password.equals(this.check_password)){
return this.check_password_condition=true;
}
else return this.check_password_condition=false;
}
//return this.password != null && this.password.equals(this.check_password) : this.setCheck_password(); }
public String getName() {
return name;
}
public String getPassword() { return password; }
public String getCheck_password(){return check_password;}
public String getAddress() {
return address;
}
}
Please help to solve this problem when
error info from Whitelabel errorpage is:
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#fields.hasErrors('*')" (template: "register" - line 29, col 42)
at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:290)
at org.thymeleaf.standard.expression.VariableExpression.executeVariableExpression(VariableExpression.java:166)
at org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:66)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:109)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:138)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:125)

It may not fully solve your issue, but looks like your String comparison is incorrect, as you shouldn't use ==.
Instead, use the String#equals() method or even Objects.equals(). This answer provider a great explanation on this.
Here's what your code can be like:
#AssertTrue
public boolean checkPasswod() {
return Objects.equals(check_password, password);
}

Related

Spring MVC #ExceptionHandler does not catch MethodArgumentNotValidException

I wanted to create a registration form where the passed data is observed whether it is valid or not.
Here is my code:
#Controller
public class RegistrationController {
#Autowired
private UserService userService;
#GetMapping("/register")
public String registration(Model model) {
model.addAttribute("user", new RegistrationRequest());
return "register";
}
#PostMapping("/register")
public String register(#Valid #ModelAttribute("user") RegistrationRequest user,
HttpServletResponse response) {
String token = userService.registerUser(user);
response.addHeader("Set-Cookie", token + "; HttpOnly; Secure; SameSite=Lax;");
return "index";
}
#ExceptionHandler(MethodArgumentNotValidException.class)
public String handleIncorrectRequests(MethodArgumentNotValidException ex, Model model) {
String errorFields = ex.getBindingResult()
.getAllErrors().stream()
.map(err -> ((FieldError) err)
.getField())
.distinct()
.collect(Collectors.joining(", "));
String message = String.format("The next fields are incorrectly filled: %s!",
errorFields);
model.addAttribute("error", "Registration failed");
model.addAttribute("cause", message);
return "error";
}
#ExceptionHandler(EmailAlreadyInUseException.class)
public String handleEmailAlreadyInUse(Model model) {
model.addAttribute("error", "Registration failed");
model.addAttribute("cause", "The given email is already being used! Please try with a different one!");
return "error";
}
}
Here is the RegistrationRequest's implementation:
#Data
#ValidateConfirmPassword
public class RegistrationRequest {
#NotBlank
#Size(min = 4 ,max = 100)
private String username;
#NotBlank
private String email;
#NotBlank
#Size(min = 6)
private String password;
#NotBlank
#Size(min = 6)
private String confirmPassword;
}
The additional validator classes:
#Documented
#Constraint(validatedBy = ConfirmPasswordValidator.class)
#Target( { ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
public #interface ValidateConfirmPassword {
String message() default "Confirm password not matches the password!";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class ConfirmPasswordValidator implements ConstraintValidator<ValidateConfirmPassword, RegistrationRequest>{
#Override
public boolean isValid(RegistrationRequest value, ConstraintValidatorContext context) {
return value.getPassword().equals(value.getConfirmPassword());
}
}
When the data is valid the system does its job, but when any constraint violation happen I get the following log and bad request screen:
[36m.w.s.m.s.DefaultHandlerExceptionResolver[0;39m [2m:[0;39m Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: ... (list of incorrectly filled fields)
I have no clue why the ExceptionHandler does not catch it, while the other one for EmailAlreadyInUseException works properly. Any help would be a blessing.

Non bean property throwing Bean property is not readable or has an invalid getter method

So my issue is a bit different from others. The error that it is throwing is not a field name but rather the input in a form. I've never encountered this error before
Error. The contents of '' is what I key for password
org.springframework.beans.NotReadablePropertyException: Invalid
property 'Yijian#123' of bean class [com.Alex.UserPackage.User]: Bean
property 'Yijian#123' is not readable or has an invalid getter method:
Does the return type of the getter match the parameter type of the
setter? at
org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:622)
~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at
org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:612)
~[spring-beans-5.2.7.RELEASE.jar:5.2.7.RELEASE] at
org.springframework.validation.AbstractPropertyBindingResult.getActualFieldValue(AbstractPropertyBindingResult.java:104)
~[spring-context-5.2.7.RELEASE.jar:5.2.7.RELEASE]
Entity class
#Entity
#ValidPassword
public class User {
#Pattern(regexp="[a-zA-Z]+", message = "Enter letters only!")
private String firstName;
#Pattern(regexp="[a-zA-Z]+", message = "Enter letters only!")
private String lastName;
private String password;
private String matchingPassword;
private String passportNumber;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMatchingPassword() {
return matchingPassword;
}
public void setMatchingPassword(String matchingPassword) {
this.matchingPassword = matchingPassword;
}
}
#ValidPassword custom annotation. The error started to occur after I used the getters for password and matchingPassword
private String message;
#Override
public boolean isValid(User user, ConstraintValidatorContext context) {
String password = user.getPassword();
String matchingPassword = user.getMatchingPassword();
if (password== null || matchingPassword == null) {
return false;
}
System.out.println("PASSWORDS: " + password + matchingPassword);
boolean flag = Pattern.matches("^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{8,}$", password);
boolean flag1 = password.equals(matchingPassword);
if ( !flag1 ) {
message = "Passwords do not match!";
}
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message)
.addPropertyNode(password).addConstraintViolation();
return flag && flag1;
}
//Show default message if no special message is set
#Override
public void initialize(ValidPassword validPassword) {
message = validPassword.message();
}
Form password portion
<div class = "row">
<div class="col-sm-6 form-group">
<label>Password : </label> <Input type="password"
th:field="*{password}" th:required="required" class="form-control" />
<p th:if="${#fields.hasErrors('password')}"
th:errors="*{password}" class="alert alert-danger"></p>
</div>
You are passing the property value instead of the property name to addPropertyNode(password).
Replace the following:
context.buildConstraintViolationWithTemplate(message)
.addPropertyNode(password).addConstraintViolation();
with:
context.buildConstraintViolationWithTemplate(message)
.addPropertyNode("password").addConstraintViolation();

Spring Boot Adding Model to the View with Thymeleaf and MVC

Ok, so I'm trying to put an attribute of an object from the model to the view as a list using thymeleaf, spring boot and jpa, I've been reading over the code for hours and I can't seem to spot my problem, also in the same application I have a very similar function working so I sort of know how to do it, but I just cannot seem to figure out this one. I keep getting an error Property or field 'question' cannot be found on null. I have no idea where I'm going wrong. The object I'm have is called QuestionAnswerSet, and I have a question string and an answer string in the database, that I can submit through the app, so it's not a problem with the database. Also everything is good with my pom file because as I said earlier I have done a very similar function.
Here's my controller.
#Controller
public class QuestionAnswerSetController
{
private QuestionAnswerSetRepository questionAnswerSetRepo;
#RequestMapping("sets")
public String sets (ModelMap model)
{
List<QuestionAnswerSet> questionAnswerSets = questionAnswerSetRepo.findAll();
model.put("questionAnswerSets", questionAnswerSets);
return "sets";
}
#RequestMapping(value="editSet/{questionAnswerSetId}", method=RequestMethod.GET)
public String editSetGet (#PathVariable Long questionAnswerSetId, ModelMap model)
{
return "editCourse";
}
#RequestMapping(value="createSet", method=RequestMethod.GET)
public String createSetGet (ModelMap model)
{
QuestionAnswerSet questionAnswerSet = new QuestionAnswerSet();
model.put("questionAnswerSet", questionAnswerSet);
return "createSet";
}
#RequestMapping(value="createSet", method=RequestMethod.POST)
public String createSetPost (#ModelAttribute QuestionAnswerSet questionAnswerSet, ModelMap model)
{
questionAnswerSetRepo.save(questionAnswerSet);
return "redirect:/sets";
}
#Autowired
public void setQuestionAnserSetRepo(QuestionAnswerSetRepository questionAnserSetRepo) {
this.questionAnswerSetRepo = questionAnserSetRepo;
}
}
Here's my html
<div th:each="Set : ${questionAnswerSets}" th:object="${questionAnswerSet}">
<span th:text="${questionAnswerSet.question}"></span>
</div>
<div th:if="${#lists.isEmpty(questionAnswerSets)}">
There is no sets to display.
</div>
Here's my repository, it's pretty standard, just though I would include it
public interface QuestionAnswerSetRepository extends JpaRepository<QuestionAnswerSet, Long> {
}
And here's my QuestionAnswerSet.java object, which is what I'm trying to return as a list
#Entity
public class QuestionAnswerSet {
private Long id;
private String question;
private String answer;
private User user;
#Id
#GeneratedValue
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
#ManyToOne
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
And Here's the error in my console
org.springframework.expression.spel.SpelEvaluationException: EL1007E:(pos 0): Property or field 'question' cannot be found on null
Yup, that should be pretty straightforward, here is the exception :
Property or field 'question' cannot be found on null
Spring EL tries to evaluate the below :
<div th:each="Set : ${questionAnswerSets}" th:object="${questionAnswerSet}">
<span th:text="${questionAnswerSet.question}"></span>
</div>
And it is unable to find questionAnswerSet ,which is null hence the error.
Use something like this :
<div th:each="questionAnswerSet : ${questionAnswerSets}">
<span th:text="${questionAnswerSet.question}"></span>
</div>
Refer Doc :
http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#using-theach

Unable to fix: 'java.lang.String' to required type 'java.util.Collection'

I'm getting this error when I submit my form and cannot figure out why this is happening. I believe the taglib should be handling this. I've tried changing the value passed in my jsp to itemValue="id" but it has no affect.
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'content' on field 'stateCollection': rejected value [com.myapp.cmt.model.State[ id=3 ]]; codes [typeMismatch.content.stateCollection,typeMismatch.stateCollection,typeMismatch.java.util.Collection,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [content.stateCollection,stateCollection]; arguments []; default message [stateCollection]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Collection' for property 'stateCollection'; nested exception is java.lang.IllegalStateException:
Cannot convert value of type [java.lang.String] to required type [com.myapp.cmt.model.State] for property 'stateCollection[0]': no matching editors or conversion strategy found]
My jsp
<strong>State</strong><br/>
<form:checkboxes path="stateCollection" items="${states}" itemLabel="name"/>
My Content
public class Content implements Serializable {
.......
#JoinTable(name = "content_to_state", joinColumns = {
#JoinColumn(name = "content_id", referencedColumnName = "id")}, inverseJoinColumns = {
#JoinColumn(name = "state_id", referencedColumnName = "id")})
#ManyToMany
private Collection<State> stateCollection;
.....
#XmlTransient
public Collection<State> getStateCollection() {
return stateCollection;
}
public void setStateCollection(Collection<State> stateCollection) {
this.stateCollection = stateCollection;
}
.....
My Controller
...
#RequestMapping(value = "/{guid}/save", method = RequestMethod.POST)
public ModelAndView saveContent(#ModelAttribute("content") Content content, #PathVariable("guid") String guid) {
try {
// Save the modified object
contentService.save(content);
} catch (IllegalOrphanException ex) {
...
My content service
...
#Transactional
public void save(Content content) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
try {
utx.begin();
em.merge(content);
utx.commit();
} catch (Exception ex) {
} finally {
if (em != null) {
em.close();
}
}
}
...
Your title isn't correct. You have declared a Collection<State> your input is a String. Spring couldn't know how to make a State from a String, you have to tell it. Please see this question: Converting from String to custom Object for Spring MVC form Data binding?
I had the same problem. i'm using Spring, Hibernate.
I have one class with composite primary key and pass two parameters in request, my mistake was:
#Entity
#Table(name = "TAREAS")
public class Tarea implements Serializable {
private static final long serialVersionUID = 1L;
protected TareaPK clave;
private String descripcion;
.....
}
the controller:
#RequestMapping(value = "/tareas", params = {"clave", "tipot"}, method = RequestMethod.GET)
public String formularioTareaEditar(
#RequestParam(value = "clave") String clave,
#RequestParam(value = "tipot") String tipoTrabajo,
Model model) {
Tarea tarea = catalogoService.getTarea(tipoTrabajo, clave);
model.addAttribute(tarea);
return "tarea/editar";
}
#RequestMapping(value = "/tareas", params = {"clave", "tipot"}, method = RequestMethod.POST)
public String tareaEditar(#Valid #ModelAttribute Tarea tarea, BindingResult result) {
if (result.hasErrors()) {
return "tarea/editar";
} else {
catalogoService.edit(tarea);
return "redirect:/tareas";
}
}
So... when the info gets in the controller the parameter clave is considered as if the object TareaPK of the primary key.
i just change the name of the parameter in my controller.
#RequestMapping(value = "/tareas", params = {"txt_clave", "tipot"}, method = RequestMethod.GET)
public String formularioTareaEditar(...){
...
}

Spring MVC Pre Populate Checkboxes

First little background info. Got a fairly standard User Role relationship where the User can have many roles. I have roles defined as a set within the user class. Now I know that html forms have all the values as strings and trying to get values as my custom Role object does not work. I implemented an initbinder to convert the id's back into object so that I can retrieve the selected values off of my checkboxes, that part works.
But I can't seem to go back the other way. I retrieve a User from the database that already has roles and want to pre populate role checkboxes with all the roles that a user has. Based on this example :
Checkboxes example
They say that:
form:checkboxes items="${dynamic-list}" path="property-to-store"
For multiple checkboxes, as long as the “path” or “property” value is
equal to any of the “checkbox values – ${dynamic-list}“, the matched
checkbox will be checked automatically.
My interpretation of that is I should be able to feed it a Set of all the roles and define the path to be the roles from the User object and it should match them thus causing the check box to pre populate.
Every example out there seems to have the value of dynamic-list as a String[]. Well thats great and dandy but how does this work for custom objects that our defined as a Set? Can I still use this one line definition for checkboxes or do I need to do some kind of data binding heading into the view also?
Here is my user dto, user controller, custom form binder, and user edit page.
User DTO
#Entity
#Table
public class User extends BaseDto
{
#Column(updatable = false) #NotBlank
private String username;
#Column(name = "encrypted_password") #Size(min = 6, message = "password must be at least 6 characters") #Pattern(regexp = "^\\S*$", message = "invalid character detected")
private String password;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column #NotNull
private boolean enabled;
#Column #Email #NotBlank
private String email;
#Transient
private String confirmPassword;
#ManyToMany(targetEntity = Role.class, fetch = FetchType.EAGER, cascade = CascadeType.REFRESH) #JoinTable(name = "user_role", joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Role> roles;
public User()
{
}
public User(final String usernameIn, final String passwordIn, final String firstNameIn, final String lastNameIn, final String emailIn, final boolean enabledIn)
{
username = usernameIn;
password = passwordIn;
firstName = firstNameIn;
lastName = lastNameIn;
email = emailIn;
enabled = enabledIn;
}
public String getUsername()
{
return username;
}
public void setUsername(final String usernameIn)
{
username = usernameIn;
}
public String getPassword()
{
return password;
}
public void setPassword(final String passwordIn)
{
password = passwordIn;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(final String firstNameIn)
{
firstName = firstNameIn;
}
public String getLastName()
{
return lastName;
}
public void setLastName(final String lastNameIn)
{
lastName = lastNameIn;
}
public String getEmail()
{
return email;
}
public void setEmail(final String emailIn)
{
email = emailIn;
}
public String getConfirmPassword()
{
return confirmPassword;
}
public void setConfirmPassword(final String confirmPasswordIn)
{
confirmPassword = confirmPasswordIn;
}
public boolean isEnabled()
{
return enabled;
}
public void setEnabled(final boolean enabledIn)
{
enabled = enabledIn;
}
public Set<Role> getRoles()
{
return roles;
}
public void setRoles(final Set<Role> rolesIn)
{
roles = rolesIn;
}
}
User Controller
#Controller #RequestMapping("/user")
public class UserController
{
#Autowired private UserService userService;
#Autowired private UserDao userDao;
#Autowired private RoleDao roleDao;
#InitBinder
public void bindForm(final WebDataBinder binder)
{
binder.registerCustomEditor(Set.class, "roles", new CustomFormBinder<RoleDao>(roleDao, Set.class));
}
#RequestMapping(method = RequestMethod.GET)
public String index(final ModelMap modelMap)
{
return "/user/index";
}
#RequestMapping(value = "/create", method = RequestMethod.GET)
public String create(final ModelMap modelMap)
{
modelMap.addAttribute("userInstance", new User());
modelMap.addAttribute("validRoles", new HashSet<Role>(roleDao.findAll()));
return "/user/create";
}
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(final ModelMap modelMap, #Valid #ModelAttribute("userInstance") final User user, final BindingResult bindingResult)
{
// TODO move to service validation
if (user.getPassword() == null || !user.getPassword().equals(user.getConfirmPassword()) )
{
bindingResult.addError(new FieldError("userInstance", "password", "password fields must match"));
bindingResult.addError(new FieldError("userInstance", "confirmPassword", "password fields must match"));
}
if (user.getRoles() == null || user.getRoles().isEmpty())
{
bindingResult.addError(new FieldError("userInstance", "roles", "Must select at least one role for a User"));
}
if (bindingResult.hasErrors())
{
modelMap.addAttribute("validRoles", new HashSet<Role>(roleDao.findAll()));
return "/user/create";
}
userService.save(user);
return "redirect:/user/list";
}
#RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
public String edit(#PathVariable final Integer id, final ModelMap modelMap)
{
final User user = userDao.find(id);
if (user != null)
{
modelMap.addAttribute("userInstance", user);
modelMap.addAttribute("validRoles", new HashSet<Role>(roleDao.findAll()));
return "/user/edit";
}
return "redirect:/user/list";
}
#RequestMapping(value = "/edit", method = RequestMethod.GET)
public String editCurrent(final ModelMap modelMap)
{
return edit(userService.getLoggedInUser().getId(), modelMap);
}
#RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(#Valid #ModelAttribute("userInstance") final User user, final BindingResult bindingResult)
{
if (bindingResult.hasErrors())
{
return "/user/edit";
}
userService.save(user);
return "redirect:/user/list";
}
#ModelAttribute("userInstances")
#RequestMapping(value = "/list", method = RequestMethod.GET)
public List<User> list()
{
return userDao.findAll();
}
}
Custom Form Binder
public class CustomFormBinder<T extends GenericDao> extends CustomCollectionEditor
{
private final T dao;
private static final Logger LOG = LoggerFactory.getLogger(CustomFormBinder.class);
public CustomFormBinder(final T daoIn, final Class collectionType)
{
super(collectionType, true);
dao = daoIn;
}
#Override
protected Object convertElement(final Object element)
{
try
{
// forms should return the id as the itemValue
return dao.find(Integer.valueOf(element.toString()));
}
catch (NumberFormatException e)
{
LOG.warn("Unable to convert " + element + " to an integer");
return null;
}
}
}
User Edit View
<html>
<head>
<title>Create User</title>
</head>
<body>
<c:url value="/user/update" var="actionUrl"/>
<form:form method="post" commandName="userInstance" action="${actionUrl}">
<h1>Edit User ${userInstance.username}</h1>
<div>
<form:label path="username">Username:</form:label>
<form:input path="username" id="username" readonly="true"/>
</div>
<div>
<form:label path="password">Password:</form:label>
<form:input path="password" id="password" type="password" readonly="true"/>
<tag:errorlist path="userInstance.password" cssClass="formError"/>
</div>
<div>
<form:label path="firstName">First Name:</form:label>
<form:input path="firstName" id="firstName"/>
<tag:errorlist path="userInstance.firstName" cssClass="formError"/>
</div>
<div>
<form:label path="lastName">Last Name:</form:label>
<form:input path="lastName" id="lastName"/>
<tag:errorlist path="userInstance.lastName" cssClass="formError"/>
</div>
<div>
<form:label path="email">Email:</form:label>
<form:input path="email" id="email" size="30"/>
<tag:errorlist path="userInstance.email" cssClass="formError"/>
</div>
<div>
**<%--Want to Pre Populate these checkboxed--%>
<form:checkboxes title="Assigned Roles:" path="roles" id="roles" items="${validRoles}" itemLabel="displayName" itemValue="id" element="div"/>**
<tag:errorlist path="userInstance.roles" cssClass="formError"/>
</div>
<form:hidden path="enabled"/>
<form:hidden path="id"/>
<form:hidden path="version"/>
<div class="submit">
<input type="submit" value="Update"/>
Cancel
</div>
</form:form>
</body>
</html>
You need a correct implemented equals method for Role!
If this is not enough have a look at class oorg.springframework.web.servlet.tags.form.AbstractCheckedElementTag. The method void renderFromValue(Object item, Object value, TagWriter tagWriter) is where the the checked flag is set.

Resources