0

我正在使用jsp和struts2,并且我有以下场景:

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

当这个表单被提交时,OGNL 表达式employee.name(相当于getEmployee().setName())在“save”方法之前被执行。而且,“empId”的值在 getEmployee() 方法中不可用。“empId”的值仅在“save”方法中可用。是否可以在 getEmployee() 中获取“empId”的值?

以下是我的 Action 类中的代码:

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;
}
4

2 回答 2

0

我不确定我是否理解清楚,您想调用 getEmployee() 并且您不知道如何在方法中获取员工 ID?

假设您有一张员工表。我们还假设该表提供了以下详细信息:

  • 员工姓名
  • 员工ID

让我们假设每一行中也有一个链接,单击该链接会将您带到该员工的员工详细信息屏幕。由于您刚刚打印了员工 ID,您还可以使用所需的 get 参数构造一个 html 锚元素,因此当调用该操作时,您将拥有所需的内容。<s:a>标签和<s:param>标签使这很容易。

有关如何使用 struts2 锚标记和属性标记的示例,请在此处查看我的回答Tiles2 Struts Switch Locale 。尽管该示例使用静态属性,但只需将参数标记中的 value 属性替换为 id 变量。

有关详细信息,请参阅http://struts.apache.org/2.2.1.1/docs/a.html 。

编辑:我现在知道在您进行编辑之前我已经很远了。

我认为最简单的方法是创建一个 getEmployee(int id) 方法。然后你也可以摆脱隐藏的字段值。在那之后它应该是直截了当的......

您的 jsp 大致如下(未经测试):

<s:form>
   <s:textfield name="%{employee[123].name}"/>
   <s:submit action="save"/>
</s:form>
于 2011-03-09T20:48:56.257 回答
0

首先,我假设您确实有该empId字段的设置器(您没有显示一个),并且您的问题是设置参数的顺序是任意的。

有一个选项ParametersInterceptor可以强制它首先设置顶级属性。您可以通过自定义拦截器堆栈以使用ordered属性集定义参数拦截器来启用它。

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

然后,在您的操作类中,将setEmpId方法更改为:

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>
于 2011-03-10T03:14:55.650 回答