4

我有一个从用户(例如日期)接收一些参数的操作。此操作会生成许多不同的报告,因此它有许多不同的方法。我需要在每种方法之前调整这些参数(将时间设置为午夜)。该prepare方法在参数绑定之前执行。是否有任何其他拦截器或任何其他约定允许我这样做?

4

2 回答 2

3

另一种方法(如果您现在正在编码则便宜,如果您已经对所有内容都进行了编码则昂贵)是将您必须在单个 Struts2 Action 中执行的每个操作模块化。

然后,您将拥有类似 an 的内容,其中包含使用而不是BaseReportAction共享的所有常见属性和方法,对方法中的参数和常见操作进行调整;protectedprivateexecute()

每个扩展 BaseReportAction 的报告都有一个 Action,比方说

ExcelReportAction、PdfReportAction 等...

或者

MinimalReportAction、CompleteReportAction 等...

或者也

DailyReportAction、MonthlyReportAction 等...

唯一的要求是super.execute();作为每个子 Actionexecute()方法的第一条语句。

通过这种方式,您可以利用继承,拥有许多更小、更干净(最终打包成几个子包)的 Action,而不是一个包含许多方法的巨大 Action。

少数报告使用的所有实用程序方法仅适用于这些报告,而不适用于所有其他报告(例如 PDF 和 XLS 的东西)......

对于不同的操作,您也可以从 XML 验证中受益(也许一个报告需要来自另一个报告的不同输入)。

最后,您的调整代码将是线程安全的(动作是线程安全的,拦截器不是)。

但如前所述,这是一种更适合预编码阶段的实现选择(即使重构并不难,根据 Web 应用程序的大小......)。

于 2012-11-21T11:19:43.733 回答
2

使用<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. -->

如果您使用的是Convention 插件,请将其应用于操作

@Action(value="action1", interceptorRefs=@InterceptorRef("paramsPrepareParamsStack"))
于 2012-11-21T10:47:06.673 回答