How to set the property value for model object in action class using ModelDriven in Struts 2?

339 views Asked by At

Using this code:

StudentAction.java:

public class StudentAction extends ActionSupport implements ModelDriven {

    private List studentList;
    Student student;
    StudentDAO sdo = new StudentDAO();
   
    public String delete() {
        System.out.println("delete action");
        System.out.println(student.getId()); //not setting value of id
        
        sdo.delete(student.getId());

        return SUCCESS;
    }

  @Override
  public Object getModel() {
    return student;
 }
 //getter and setter
}

Student.java:

public class Student  implements java.io.Serializable {
    private Long id;
    private String name;
    private String address;
    //getter and setter
}

In JSP:

<s:iterator value="studentList" var="ss">
    <s:property value="id"/>
    <s:property value="name"/>
    <s:property value="address"/>
    <a href="delete?id= <s:property value="id"/>">delete</a><br>
</s:iterator><br>

When I pass the value of id from JSP to delete action I want to initialize Student's id property.

How to do this?

1

There are 1 answers

5
Roman C On

Use the action field to set the parameter id:

public class StudentAction extends ActionSupport {

    private List studentList;
    Student student;
    StudentDAO sdo = new StudentDAO();
     private Long id;
    //getter and setter


    public String delete() {
        System.out.println("delete action");
        System.out.println(getId()); 

        sdo.delete(getId());

        return SUCCESS;
    }
}

One more thing if you want to implement ModelDriven you should add the code for your model

private Student model = new Student();

public Object getModel() {
  return model;
}

The code is like in the documentation example.