vendredi 27 février 2015

Get bean from select tag on jsp page

I use Spring, jsp and Hibernate in my project. I have two entities Employee and Department. Dapartment is a part of Employee and they have relationship one-to-many



@Entity
@Table(name = "employee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToOne
@JoinColumn(name = "dep_id")
private Department department;


I create controller, DAO and jsp pages for view.


My problem: I want to update data of Employee in my jsp page. Before this I add Employee and list of departments in model


In controller:



model.addAttribute("employee", employeeDao.find(id));
model.addAttribute("departments", departmentDao.list());


In JSP:



<form method="post">
<select value="${employee.department}">
<c:forEach items="${departments}" var ="dep">
<option value="${dep}">${dep.name}</option>
</c:forEach>
</form>


In controller (post request)



@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public String updateEmployee(@PathVariable("id") long id, Employee employee) {
employee.setId(id);
employeeDao.update(employee);

return "redirect:/employees";
}


but value employee.department=null Why?


Of course, on jsp page in "select" tag I can create variable dep I mean:



<select name ="dep">
<option value="${dep.id}">${dep.name}</option>
</select>


and then in controller using id of department i will be able to get department from database and update Employee. Is it right way?


Aucun commentaire:

Enregistrer un commentaire