get selected value in controller - jsp/spring - spring

I am trying to pass value from in jsp to POST controller.
i have the controller get:
#RequestMapping(value = "/matches/{pageNumber}/", method = RequestMethod.GET)
public String games( #PathVariable Integer pageNumber, Model model ) {
....
//build map for dropdown compatitions
HashMap<Integer, String> leaguesMap = new HashMap<Integer, String>();
leaguesMap.put(1, "Top Leagues");
leaguesMap.put(2, "All");
for (Competition competition : competitions) {
if(!leaguesMap.containsKey(competition.getApiId())){
leaguesMap.put(competition.getApiId(), competition.getName());
}
}
model.addAttribute("leaguesMap", leaguesMap);
.....
return "upcomingMatches";
}
And then in jsp:
<form:form modelAttribute="leaguesMap" action="drop" class="dropdown-leagues" method="POST">
<form:select path="${leaguesMap.value}" id="league-selection" onchange="this.form.submit()" class="form-control select-filter select2-hidden-accessible" aria-hidden="true">
<form:options items="${leaguesMap}" />
</form:select>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form:form>
I am trying to get the selected value in POST controller:
#RequestMapping(value = "/matches/{pageNumber}/drop", method = RequestMethod.POST)
public String games( #ModelAttribute("leaguesMap") String leaguesMap, #PathVariable Integer pageNumber, BindingResult result) {
String fff = leaguesMap;
System.out.println("asadasdadsa"+fff);
return "redirect:/matches/{pageNumber}/";
}
But getting always null.
If you can give me direction how to proceed , it will be great.
Thanks!

Create a model class League.class
public class League {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Change your get controller:
#RequestMapping(value = "/matches/{pageNumber}/", method = RequestMethod.GET)
public String games( #PathVariable Integer pageNumber, Model model ) {
....
//build map for dropdown compatitions
HashMap<Integer, String> leaguesMap = new HashMap<Integer, String>();
leaguesMap.put(1, "Top Leagues");
leaguesMap.put(2, "All");
for (Competition competition : competitions) {
if(!leaguesMap.containsKey(competition.getApiId())){
leaguesMap.put(competition.getApiId(), competition.getName());
}
}
model.addAttribute("leaguesMap", leaguesMap);
model.addAttribute("league", new League());
.....
return "upcomingMatches";
}
Change your jsp:
<form:form modelAttribute="league" action="drop" class="dropdown-leagues" method="POST">
<form:select path="id" id="league-selection" onchange="this.form.submit()" class="form-control select-filter select2-hidden-accessible" aria-hidden="true">
<form:options items="${leaguesMap}" />
</form:select>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form:form>
And finally your post controller:
#RequestMapping(value = "/matches/{pageNumber}/drop", method = RequestMethod.POST)
public String games( #ModelAttribute("league") League league, #PathVariable Integer pageNumber, BindingResult result) {
System.out.println("asadasdadsa" + league.getId());
return "redirect:/matches/{pageNumber}/";
}

Related

How to create java spring-mvc form with hibernate #OneToOne,#ManyToOne... annotations with #ModelAttribute

I want to create a controller with #ModelAttribute which allows me to insert to my Customer table data. I've done one with the employee but how can I save two hibernate mapped entities in JSP form with #ModelAttribute? also, I'm using basic generated repositories with JpaRepository interface. I want to make those two entities in relation saving it.
I tried to make #ModelAttribute JSP forms, but I don't know how to set other table entity in relation.
Employee
#Entity
#Table
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
#Digits(integer = 10, fraction = 0, message = "Must be a digit")
private Integer age;
private BigDecimal salary;
#Temporal(TemporalType.DATE)
#DateTimeFormat(pattern = "yyyy-MM-dd")
#PastOrPresent(message = "Date must be past or present")
private Date birthDate;
#Temporal(TemporalType.DATE)
#DateTimeFormat(pattern = "yyyy-MM-dd")
#PastOrPresent(message = "Date must be past or present")
private Date hireDate;
private boolean sex; //false - woman, true - man
#OneToOne(mappedBy = "employee")
private Address address;
public Employee() {
}
public Employee(String firstName, String lastName, Integer age, BigDecimal salary, Date birthDate, Date hireDate,
boolean sex) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.salary = salary;
this.birthDate = birthDate;
this.hireDate = hireDate;
this.sex = sex;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public Date getHireDate() {
return hireDate;
}
public void setHireDate(Date hireDate) {
this.hireDate = hireDate;
}
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address
#Entity
#Table
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String country;
private String city;
private String street;
private Integer houseNumber;
private Integer local;
private String postalCode;
#OneToOne
#JoinColumn(name = "employee_id")
private Employee employee;
public Address() {
}
public Address(String country, String city, String street, Integer houseNumber, Integer local, String postalCode) {
this.country = country;
this.city = city;
this.street = street;
this.houseNumber = houseNumber;
this.local = local;
this.postalCode = postalCode;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public Integer getHouseNumber() {
return houseNumber;
}
public void setHouseNumber(Integer houseNumber) {
this.houseNumber = houseNumber;
}
public Integer getLocal() {
return local;
}
public void setLocal(Integer local) {
this.local = local;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
Controller
#Controller
#RequestMapping("/user")
public class UserController {
#Autowired
public EmployeeService employeeService;
#Autowired
public AddressService addressService;
#GetMapping("/add")
public String addUser(Model model) {
model.addAttribute("employee", new Employee());
return "user/addEmployee";
}
#PostMapping("/add")
public String postAddUser(#Valid #ModelAttribute("employee") Employee employee, BindingResult bs) {
if(bs.hasErrors()) {
return "user/addAddress";
} else {
employeeService.saveOrUpdate(employee);
return "user/success";
}
}
#GetMapping("/address/add")
public String addAddress(Model model) {
List<Employee> employees = employeeService.findAll();
model.addAttribute("employees", employees);
model.addAttribute("address", new Address());
return "user/addAddress";
}
#PostMapping("/address/add")
public String postAddAddress(#ModelAttribute("address") Address address, #RequestParam("employee_id") Long id) {
Employee employee = employeeService.findById(id);
address.setEmployee(employee);
employee.setAddress(address);
addressService.saveOrUpdate(address);
employeeService.saveOrUpdate(employee);
return "user/addAddress";
}
}
addAddress.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head></head>
<body>
<h2>Address Form</h2>
<form:form action="/user/address/add" method="POST" modelAttribute="address">
City: <form:input path="city"/><br>
Street: <form:input path="street" /><br>
House Number: <form:input path="houseNumber"/><br>
Local: <form:input path="local"/><br>
Postal Code: <form:input path="postalCode" /><br>
<select name="employee_id">
<c:forEach var="employee" items="${employees}">
<option value="${employee.id}">${employee.id} ${employee.firstName} ${employee.lastName}</option>
</c:forEach>
</select><br>
<input type="submit" />
</form:form>
</body>
</html>
addEmployee.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head></head>
<body>
<h2>Employee Form</h2>
<form:form action="/user/add" method="POST" modelAttribute="employee">
First Name: <form:input path="firstName"/> <form:errors path="firstName"></form:errors><br>
Last Name: <form:input path="lastName"/> <form:errors path="lastName"></form:errors><br>
Age: <form:input path="age" /> <form:errors path="age" type="number"></form:errors><br>
Salary: <form:input path="salary" type="number"/> <form:errors path="salary"></form:errors><br>
Birth Date<form:input path="birthDate" type="date"/> <form:errors path="birthDate"></form:errors><br>
Hire Date<form:input path="hireDate" type="date" /> <form:errors path="hireDate"></form:errors><br>
Female: <form:radiobutton path="sex" value="0" /> Male: <form:radiobutton path="sex" value="1" /><br>
<input type="submit" value="Wyślij"/>
</form:form>
</body>
</html>
I need to create a result in the database with those two entities with a relationship using #ModelAttribute. Is it possible?
If I understood your problem correctly,
To set the associated entity -
you need to have unique value to identify the entity (for ex. Employeeid for employees),
fetch the details for the Employeeid, this will result in employee entity object
set the employee entity object into customer entity object
similarly for Invoices.
then save customer entity object.
Check - https://thoughts-on-java.org/ultimate-guide-association-mappings-jpa-hibernate/
You could try to combine them something like this:
<form:form action="add" method="POST" modelAttribute="employee">
<form:hidden path="id"/>
First Name: <form:input path="firstName"/> <form:errors path="firstName"></form:errors><br>
Last Name: <form:input path="lastName"/> <form:errors path="lastName"></form:errors><br>
Age: <form:input path="age" /> <form:errors path="age" type="number"></form:errors><br>
Salary: <form:input path="salary" type="number"/> <form:errors path="salary"></form:errors><br>
Birth Date<form:input path="birthDate" type="date"/> <form:errors path="birthDate"></form:errors><br>
Hire Date<form:input path="hireDate" type="date" /> <form:errors path="hireDate"></form:errors><br>
Female: <form:radiobutton path="sex" value="0" /> Male: <form:radiobutton path="sex" value="1" /><br>
<form:form action="add" method="POST" modelAttribute="address">
<form:hidden path="addressId"/> // <- need to rename in your entity Address class
City: <form:input path="city"/><br>
Street: <form:input path="street" /><br>
House Number: <form:input path="houseNumber"/><br>
Local: <form:input path="local"/><br>
Postal Code: <form:input path="postalCode" /><br>
<select name="employee_id">
<c:forEach var="employee" items="${employees}">
<option value="${employee.id}">${employee.id} ${employee.firstName} ${employee.lastName}</option>
</c:forEach>
</select><br>
<input type="submit" value="Submit"/>
</form:form>
<input type="submit" />
</form:form>
In controller method:
#PostMapping("/add")
public String postAdd(#ModelAttribute("employee") #Valid Employee employee
BindingResult empBindingResult,
#ModelAttribute("address") Address address,
BindingResult addressBindingResult) {
// other code
}
Although I didn't use radiobutton and selector elements in this combination, the rest of code should work fine.
Spring MVC Multiple ModelAttribute On the Same Form
Multiple modelattributes in a JSP with Spring

Springs form null values

I have a small problem with my form in spring, it is a simple form with title, username and password, validation works as if I try to submit an empty form I get an error however if I input values in and submit the form, it is submitted but it displays that values inserted are "null".
Domain:
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
#NotNull
#Size(min=2, max=30)
private String username;
#NotNull
#Size(min=6)
private String password;
public String getTitle() { return title; }
public String getUsername() { return username; }
public String getPassword() { return password; }
public Long getId() { return id; }
public void setId(Long id) {
this.id = id;
}
public void setUsername(String username) { this.username = username; }
public void setPassword(String password) { this.password = password; }
public void setTitle(String title) { this.title = title; }
public List<Note> getNotes() {
return notes;
}
#OneToMany
private List<Note> notes = new ArrayList<Note>();
}
Form:
<form action="#" th:action="#{/create/user}" th:object="${user}" method="post">
<input type="hidden" th:field="*{id}" />
<p>Title: <input type="text" th:field="*{title}" /></p>
<p>Username: <input type="text" th:field="*{username}" /></p>
<p>Password: <input type="password" th:field="*{password}" /></p>
<p><input type="submit" value="Submit" /></p>
</form>
<div class="form-group">
<ol class="list-group">
<li class="list-group-item list-group-item-info" th:each="user : ${user}">
<span th:text=" ${user.title} + ${user.username} + ${user.password} "></span>
delete
</li>
</ol>
</div>
Controller:
#Controller
public class UserController {
#Autowired
protected UserService userService;
#RequestMapping(value = "/create/user", method = RequestMethod.POST)
public String createUser(Model model, #Valid #ModelAttribute("user") User user, BindingResult bindingResult){
if(bindingResult.hasErrors()){
model.addAttribute("user", user);
model.addAttribute("users", userService.findAll());
model.addAttribute("type", "danger");
model.addAttribute("message", "Please fill in all the fields" +
"Username needs to be at least 2 characters" +
"Passwords needs to contain at least 6 characters");
return "user";
}
userService.save(user);
model.addAttribute("user", new User());
model.addAttribute("cards", userService.findAll());
model.addAttribute("type", "success");
model.addAttribute("message", "A new user has been added");
return "user";
}
If any additional code in needed please let me know, I am still newbie in Spring
Found an error by reviewing the code:
In the form when outputting registered users it was:
<li class="list-group-item list-group-item-info" th:each="user : ${user}">
While it should be:
<li class="list-group-item list-group-item-info" th:each="user : ${users}">

Spring form binding return null with many-2-one relationship

Here is the problem, when I try to submit form, user entity returns null.
Form is
<form:form class="g-form" modelAttribute="objView" id="userAssignmentForm">
<form:hidden path="id" value="${objView.id}"/>
${objView.user.id}
<div class="g-form-group required">
<label for="user">User</label>
<form:hidden id="user" path="user" value="${objView.user}"/>
<input type="text" value="${objView.user.userName}" readonly="true"/>
<input type="button" class="import-input" onclick="gImport.showImportUserForm()"/>
</div>
Controller is
#RequestMapping(value = "/create", method = RequestMethod.POST)
public #ResponseBody
String create(
#ModelAttribute("objView") UserAssignmentView objView, BindingResult result,
SessionStatus status,
HttpServletRequest request) throws UnsupportedEncodingException {
UserAssignment obj = new UserAssignment();
obj.setUser(objView.getUser());
userAssignmentService.create(obj);
return "ok";
}
Model is below contains a view entity. What am I missing?
public class UserAssignmentView extends UserAssignment {
public UserAssignmentView() {
}
public UserAssignmentView(UserAssignment obj) {
setId(obj.getId());
setStatus(obj.getStatus());
setUser(obj.getUser());
}
}
And this is form view part of controller
#RequestMapping(value = "/form", method = RequestMethod.POST)
public ModelAndView form(HttpServletRequest request) {
UserAssignment obj = new UserAssignment();
Account account = AccountRegistry.getByHttpSession(request.getSession());
ModelAndView modelAndView = new ModelAndView("forms/userAssignmentForm");
modelAndView.addObject("objView", UserAssignmentWrapper.wrap(obj));
return modelAndView;
}
I could not solve since 3 days, how can I set user to userassignment?

how do I pass the selected parameters in the checkbox from one jsp page to another jsp page?

I have to make the switch to selected values ​​within some checkboxes in a jsp page but after the selection and after pressing the "Send" button, I generate this error with the following description: HTTP Status 400: The request sent by the client was syntactically incorrect.
Where am I wrong?
TaskController.java
#RequestMapping(value="/newTask", method = RequestMethod.GET)
public String task(#ModelAttribute Task task, Model model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String s = auth.getName();
Student student = studentFacade.retrieveUser(s);
List<Job> jobs = new ArrayList<>();
if(!(auth instanceof AnonymousAuthenticationToken)) {
jobs = facadeJob.retriveAlljobs();
model.addAttribute("job", getMathRandomList(jobs));
model.addAttribute("image", imageFacade.retriveAllImages());
List<Image> img = imageFacade.retriveAllImages();
task.setImages(img);
task.setStudent(student);
taskFacade.addTask(task);
List<Long> images = new ArrayList<>();
for(Image i : img)
images.add(i.getId());
model.addAttribute("images", images);
}
return "users/newTask";
}
#RequestMapping(value="/taskRecap", method = RequestMethod.POST)
public String taskRecap(#ModelAttribute Task task, Model model,BindingResult result) {
model.addAttribute("task", task);
return "users/taskRecap";
}
newTask.jsp
<form:form method="post" action="taskRecap" modelAttribute="task" name="form">
<form:checkboxes path="images" items="${images}" value="yes" />
<td><input type="submit" value="Send" /></td>
</form:form>
taskRecap.jsp Immages
<c:forEach var="image" items="${task.images}">
<c:out value="${image.id}" />
</c:forEach>
Task.java
#Entity
public class Task {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne
private Student student;
#ManyToMany
List<Image> images;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Task() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Task(Long id, Student student, List<Image> images) {
super();
this.id = id;
this.student = student;
this.images = images;
}
public List<Image> getImages() {
return images;
}
public void setImages(List<Image> images) {
this.images = images;
}
}
Using Query parameter
<a href="edit.jsp?Name=${user.name}" />
Using Hidden variable .
<form method="post" action="update.jsp">
<input type="hidden" name="Name" value="${user.id}">
if you use either of the first 2 methods you can access your value like this:
String userid = session.getParameter("Name");
you can send Using Session object.
session.setAttribute("Name", UserName);
These values will now be available from any jsp as long as your session is still active.
if you use the third option you can access your value like this:
String userid = session.getAttribute("Name");

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