Java struts 2多对一关联示例

Java struts 2多对一关联示例,java,hibernate,jsp,struts2,ognl,Java,Hibernate,Jsp,Struts2,Ognl,在jsp中,我使用ognl表达式作为部门列表,有两个bean类student和department。使用Hibernate多对一关联。student bean包含部门id;场 学生班 public class Student { private int id; private String studentName; private Department dept_id; public Student() {} public Student(int i

在jsp中,我使用ognl表达式作为部门列表,有两个bean类student和department。使用Hibernate多对一关联。student bean包含部门id;场

学生班

public class Student {

    private int id;
    private String studentName;
    private Department dept_id;

    public Student() {}

    public Student(int id,String studentName,Department dept_id) {
        this.id = id;
        this.studentName = studentName;
        this.dept_id = dept_id;

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public Department getDept_id() {
        return dept_id;
    }

    public void setDept_id(Department dept_id) {
        this.dept_id = dept_id;
    }
}
系级

public class Department {

    private int dept_id;
    private String deptName;

    public Department() {}

    public Department(int dept_id,String deptName) {
        this.dept_id = dept_id;
        this.deptName = deptName;
    }

    public int getDept_id() {
        return dept_id;
    }

    public void setDept_id(int dept_id) {
        this.dept_id = dept_id;
    }

    public String getDeptName() {
        return deptName;
    }

    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }
}
index.jsp

<s:form action="insertData">
<s:textfield name = "studentName" label = "Name"/>
<s:select  list="#{'1':'IT', '2':'COM', '3':'EC'}" name="dept_id" 
label="Select Department"/> 
<s:submit value = "Submit"/>
</s:form>


现在,在获取select标记值时,它是字符串,我必须以对象形式存储dept_id,因为我在数据库中使用外键。如何在action类中获取对象值?

将操作的属性绑定到表单提交一些id并在操作中从db获取。如果我理解正确,您希望能够获取字符串所在的映射是部门名称,整数是部门id?这样,当您创建/更新/删除Department表时,select仍然具有正确的键?如果是这样,您需要一个服务来获取该数据(获取所需内容的函数,您可以将其保留为一个列表),那么我个人的偏好是删除s:select以支持普通html,但我会在添加适当值的标记列表上使用s:iterator,我会发现这很清楚。实际上select标记在字符串中获取值,在bean类中它在object中设置值。所以我使用了类型转换器,问题就解决了。