问题
I put the println()
in each method of Action class.
public String execute() throws Exception {
System.out.println("execute");
//...
}
public void prepare() throws Exception {
System.out.println("prepare");
//...
}
public Object getModel() {
System.out.print("getModel");
//...
}
I thought the order would be; prepare → execute → getModel.
Because I remember I read it in the book, so I used to construct beans class and do some logics in prepare()
, and just return SUCCESS in execute()
.
And I think getModel is for pushing the bean to the valueStack, right?
...anyway the console showed me this. It's very weird; prepare → getModel → execute.
And this is becoming a huge problem to me. It's very hard to explain the reason in English... but I'll try!
I used to create each action class which is dealing with same beans, and of course there are same codes(variables, and their getters and setters) duplicated in each action class.
Now I'm trying to create one action to avoid that duplication. This action class has several methods(mapped in struts.xml like this;<action name="View_board" method="view">
).
And as we saw in the console, this view()
is called at the last in the action class like execute()
. The prepare()
does only construct beans, and the view()
does real jobs. But getModel()
is called before calling of view()
, so there's no chance to put the beans to ValueStack.
I hope you guys understand what I'm trying to explain.
To sum it up, there are each action class like BoardView, BoardDelete, BoardWrite... and they worked well! But I hate that duplicated things so I created BoardManager class. This class has each method(like view()
) which was handled by class(like BoardView). But this view() was called after the call of getModel()
, so the bean(return of getModel()
) has no chance to be pushed to the ValueStack.
Please help me out. Teach me your know-how in the field. I'm developing it all on my own and this is making me feel so hard.
Thank you!!
回答1:
You have to set the Model object yourself as the modeldriven interceptor can only push it to the stack if its not null. If your getModel() looks like this:
SomeModelClass myModelObject = null;
public Object getModel()
{
return myModelObject;
}
... you'll have to set the modelObject so it can get pushed to the valueStack. You could do it this way I guess:
public void prepare(){
myModelObject = new myModelObject("I'm so new");
}
... or just initialize it in the field:
SomeModelClass myModelObject = new myModelObject("I'm so new");
Don't forget to implement the appropriate Interfaces (ModelDriven and Preparable). Hope this helps a bit.
回答2:
I found my own solution.. but not a good one..
When setting domain object by setter, I push it to the valuestack manually..
It works good and only 2 lines added to my class.
But I don't feel that good.
来源:https://stackoverflow.com/questions/3438465/the-sequence-of-modeldriven-and-prepare