首先,set-property标记在action的内部局部使用,归属于所定义的action。set-property标记对于“向action传递信息非常有用”。例如,如果一个单独的Action可以处理若干个不同的表单,可以使用set-property标记告诉Action要处理的是哪一个表单。这种情况下,此Action的name属性定义的Form封装所有需要处理的表单字段,action根据set-property标记传入的信息来决定需要处理的表单,然后从form中取得需要的表单字段。
下面,重点介绍怎样使用set-property标记。需要提醒的是<set-property property="task" value="Mytask"/>并不是用来设置Action的属性。我看到很多人说,使用这个标记就是要给action定义一个命名为set-property所指定的属性名task的字段,并提供setter/getter访问器,像这样
+++++++++++++++++++++++++++++++++++++++++++++++++
public class LoginAction extends org.apache.struts.action.Action {
private String task;
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
}
public void setTask(String task) {
this.task = task;
}
public String getTask() {
return task;
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++
我要指出的是,这种做法是完全错误的。
正确的解释是<set-property property="task" value="Mytask"/>用来设置与Action相关联的配置类的属性。默认情况下这个配置类是org.apache.struts.action.ActionMapping,set-property设置的是ActionMapping的属性值。为了设置自定义的属性值task,需要继承ActionMapping实现一个子类,命名为MyMapping,并定义task属性,如下:
+++++++++++++++++++++++++++++++++++++++++++++++++++
public class MyMapping extends org.apache.struts.action.ActionMapping{
private static final long serialVersionUID = 1L;
private String task;
/**
* @return the task
*/
public String getTask() {
return task;
}
/**
* @param task the task to set
*/
public void setTask(String task) {
this.task = task;
}
}
+++++++++++++++++++++++++++++++++++++++++++++++++
然后在action的配置中指定与它相关联的配置类为自定义的MyMapping。比如,我们在struts配置文件中定义了LoginAction,那么它的配置是这样的:
++++++++++++++++++++++++++++++++++++++++++++++++++++
<action-mappings>
<action path="/login" name="LoginActionForm" input="/login/login.jsp"
className="com.myapp.struts.myactionmapping.MyMapping">
<!--configuration custom ActionMapping by setting className
property as custom ActionMapping
-->
<set-property property="task" value="MyTask"/>
<forward name="success" path="/welcomeStruts.jsp"/>
<forward name="error" path="/login/login.jsp"/>
</action>
</action-mappings>
+++++++++++++++++++++++++++++++++++++++++++++++++++++
这样配置后,action实例化时,对应的MyMapping的“task”属性将被设置为<set-property property="task" value="MyTask"/>
中value指定的值“MyTask”。然后可以在execute方法中通过mapping.getTask()取得其值。这种配置只影响这一个Action。如果你想让所有Action的execute方法中都可以通过mapping.getTask()取值的话,可以做如下配置:
++++++++++++++++++++++++++++++++++++++++++++++++++++
<action-mappings type="com.myapp.struts.myactionmapping.MyMapping">
<action path="/login" name="LoginActionForm" input="/login/login.jsp"
<!--configuration custom ActionMapping by setting className
property as custom ActionMapping
-->
<set-property property="task" value="MyTask"/>
<forward name="success" path="/welcomeStruts.jsp"/>
<forward name="error" path="/login/login.jsp"/>
</action>
</action-mappings>
+++++++++++++++++++++++++++++++++++++++++++++++++++++