我有这个ManagedBean:
@ManagedBean(name="studentItem")
@ViewScoped
public class StudentBean implements Serializable {
private static final long serialVersionUID = 1L;
@ManagedProperty("#{StudentService}")
private StudentService studentService;
private int regId;
private String firstName;
private String lastName;
//getters and setters
public void saveStudent(StudentBean student) {
//calling from xhtml to save form data
studentService.addStudent(student);
}
}
以及此服务的实现:
@Component
@Service("StudentService")
public class StudentServiceImpl implements StudentService {
@Autowired
private UserDao<Student> studentDao;
@Override
@Transactional
public void addStudent(StudentBean student) {
Student stu=new Student();
stu.setRegId(student.getRegId());
stu.setFirstName(student.getFirstName());
stu.setLastName(student.getLastName());
studentDao.addItem(stu);
}
}
如您所见,我不得不使用DAO方法将StudentBean
受管bean对象转换为Student
对象类型,以将其保存在数据库中。除了丑陋地逐一复制属性之外,还有其他标准方法吗?
答案 0 :(得分:1)
您违反了MVC(模型视图控制器)模式! 您有3个部分(模型=学生,视图(您的面)和控制器=学生Bean)应该是独立的。
如果我是你,我将按照以下步骤操作:
@ManagedBean(name="studentItem")
@ViewScoped
public class StudentBean implements Serializable {
private Student currentStudent;
//getter/setter
@ManagedProperty("#{StudentService}")
private StudentService studentService;
public String renderStudentForm(){
//create a new student when you load the form
currentStudent = new Student();
}
public void saveStudent(){
studentService.addStudent(currentStudent);
}
}
在表单视图中,您可以使用EL #{studentItem.currentStudent.name}
您明白了。
答案 1 :(得分:-1)
在这种情况下,有一些实用程序可以为您提供帮助。 您可以尝试BeanUtils复制属性或DozerMapper