Search code examples
jspstruts2ognl

Struts2 OGNL - Request parameters submission order


I am using jsp and struts2, and I have the following scenario:

<s:form>
<s:hidden name="empId" value="123"/>
<s:textfield name="employee.name"/>
<s:submit action="save"/>
</s:form>

When this form is submitted, the OGNL expression employee.name (equivalent to getEmployee().setName()) gets executed before "save" method. And, the value for "empId" is not available inside the method getEmployee(). The value for "empId" is available only inside the "save" method. Is it possible to get the value of "empId" inside getEmployee()?

Following is the code in my Action class:

public String save() {
  //empId is available here
  return SUCCESS;
}

public Employee getEmployee(){
  if (employee == null){
    //empId is not available here
    employee = employeeService.get(empId);
  }
  return employee;
}

Solution

  • First, I assume that you do have a setter for the empId field (you didn't show one) and that your problem is that the order in which the parameters are being set is arbitrary.

    There is an option for the ParametersInterceptor to force it to set top-level properties first. You can enable it by customizing your interceptor stack to define the parameters interceptor with the ordered property set.

    <interceptor-ref name="params">
        <param name="ordered">true</param>
    </interceptor-ref>
    

    Then, in your action class, change the setEmpId method to:

    public void setEmpId(Integer empId) { // or whatever type it is
        this.empId = empId;
        employee = employeeService.get(empId);
    }
    

    As an alternative to the setter approach, you could also create a type converter for the Employee class and then change your form to:

    <s:form>
        <s:hidden name="employee" value="123"/>
        <s:textfield name="employee.name"/>
        <s:submit action="save"/>
    </s:form>