而prepare()方法会在每个action执行时都会调用,这样未免杀伤力大了点。有时我们可能希望你针对某个action使用一个专属的prepare方法,那么操作方式如下
PREPARE (DEFAULTSTACK)
The prepare interceptor provides a generic entry point for arbitrary workflow pro-
cessing that you might want to add to your actions. The concept is simple. When the
prepare interceptor executes, it looks for a prepare() method on your action. Actu-
ally, it checks whether your action implements the Preparable interface, which
defines the prepare() method. If your action is Preparable, the prepare() method
is invoked. This allows for any sort of preprocessing to occur. Note that while
the prepare interceptor has a specific place in the defaultStack, you can define
your own stack if you need to move the prepare code to a different location in
the sequence.
The prepare interceptor is flexible as well. For instance, you can define special pre-
pare methods for the different execution methods on a single action. As we said ear-
lier, sometimes you’ll want to define more than one execution entry point on your
action. (See the CRUD example in chapter 15 for details.) In addition to the execute()
method, you might define an input() method and an update() method. In this case,
you might want to define specific preparation logic for each of these methods. If
you’ve implemented the Preparable interface, you can also define preparation meth-
ods, named according to the conventions in table 4.1, for each of your action’s execu-
tion methods.
Action Method Name | prepare method 1 | prepare method 2 |
input() | prepareInput() | prepareDoInput() |
update() | prepareUpdate() | prepareDoUpdate() |
Two naming conventions are provided. You can use either one. The use case is simple.
If your input() method is being invoked, the prepareInput() method will be called
by the prepare interceptor, giving you an opportunity to execute some preparation
code specific to the input processing. The prepare() method itself will always be
called by the prepare interceptor regardless of the action method being invoked. Its
execution comes after the specialized prepare() method. If you like, you can turn off
the prepare() method invocation with a parameter passed to the prepare interceptor:
alwaysInvokePrepare - Default to true.
The Preparable interface can be helpful for setting up resources or values before
your action is executed. For instance, if you have a drop-down list of available values
that you look up in the database, you may want to do this in the prepare() method.
That way, the values will be populated for rendering to the page even if the action isn’t
executed because, for instance, the workflow interceptor found error messages.
reference url:http://struts.apache.org/2.0.14/docs/prepare-interceptor.html