问题
I have an action that receives some parameters from user (e.g. date). This action produces many different reports, so it has many different methods. I need to tune those parameters (set a time to midnight) before every method. The prepare
method is executed before parameters are bound. Is there any other interceptor or any other convention that allows me to do that?
回答1:
Use the <interceptor-ref name="paramsPrepareParamsStack"/>
<!-- An example of the params-prepare-params trick. This stack is exactly the same as the defaultStack, except that it includes one extra interceptor before the prepare interceptor: the params interceptor. This is useful for when you wish to apply parameters directly to an object that you wish to load externally (such as a DAO or database or service layer), but can't load that object until at least the ID parameter has been loaded. By loading the parameters twice, you can retrieve the object in the prepare() method, allowing the second params interceptor to apply the values on the object. -->
If you are using the Convention Plugin apply it on action
@Action(value="action1", interceptorRefs=@InterceptorRef("paramsPrepareParamsStack"))
回答2:
Another way to go (cheap if you are coding right now, expensive if you've already coded everything) would be to modularize every action you have to perform in one single Struts2 Action.
Then you will have something like an BaseReportAction
, containing all the common attributes and methods shared using protected
instead of private
, doing your tuning on parameters and the common operations in the execute()
method;
And one Action for each report extending the BaseReportAction, let's say
ExcelReportAction, PdfReportAction, etc...
or
MinimalReportAction, CompleteReportAction, etc...
or also
DailyReportAction, MonthlyReportAction, etc...
And the only requirement would be using super.execute();
as first statement of every child Action's execute()
method.
This way you could take advantage of the inheritance, to have a lot of smaller, cleaner (eventually packaged into several sub-packages) Actions instead of one huge Action with a lots of methods.
All the utility methods used by few reports would be available only for those reports, not for all the others (let's say PDF and XLS stuff for example)...
You could benefit of the XML Validation too for different Actions (maybe one report requires different inputs from another).
Finally, your tuning-up code would be Thread-Safe (Actions are Thread-Safe, Interceptors don't).
But as said, this is a choice of implementation that better suits the pre-code phase (even if it's not that hard to refactor, according to the size of the web application...).
来源:https://stackoverflow.com/questions/13491495/changing-parameters-after-bind-in-struts-2