Thursday, 14 April 2016

How to use ModelDriven in Struts 2 ?


Two ways to collect input for Actions :

1. Model-driven
  • Action has methods returning your model classes (myAction.getUser())
  • Fields in the view are fields of your model
  • Views refer directly to your model (property=‘user.name’)
  • Excellent because it allows model reuse

2. Field-driven
  • Action has fields of its own, which are fields in the view
  • execute() collates fields and interacts with the model
  • Views refer to action fields (property=‘daysTillNextBirthday’)
  • Useful where form is not parallel to model

The two can be mixed and used.

ModelDriven Interface
  • Direct support of model-driven Actions
  • The ModelDriven Interface has one method :
    public Object getModel()
  • Properties of the model are flattened :
    “name” instead of “user.name”
  • Applies to UI tags, form field names, and so forth

public class Birthday extends ActionSupport implements ModelDriven {
   ...
   public Object getModel() {
     return user;
   }
}

Applying the ModelDrivenInterceptor
In struts.xml
<action name=“birthday" class=“happy.Birthday">
  <interceptor-ref name="modelDriven"/>
  <interceptor-ref name="defaultStack"/>
  <result>/Model/success.jsp</result>
  <result name="input">/Model/form.jsp</result>
</action>

The ModelDrivenInterceptor pushes the Model onto the ValueStack.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.