Jeremy JGR. Grumbach wrote:
Let's take the following scenario: we have a database which manage car
models (for example Dogde Viper). The column "name" of the "car model"
table must be unique.
The user wants to add a "car model" in the database, thus he has an "add
screen" containing all the fields of the "car model" and a "Save"
button. However he has entered a model which already exists in the
database. I check that in my business layer and return a runtime
exception "name already exists".
I can display it using global-exceptions, however it is forwarded to
another page and consequently, the user must reenter all the field
values one more time.
To avoid that, I want to go back to the "add screen" without losing user
inputs but with a red message "name already exists in the database" -
exactly like the struts validation error messages.
Do you think it is possible with Struts 2? I have used that lots of time
in Struts 1.
More than possible, it's actually not very hard and fairly common (at
least for me).
In the form-processing action (the one that attempts to create the car
and causes the exception to be thrown) just capture the exception and
handle that case there by...
* Store the data-structure (or structures) containing your "new car
info" (NewCar, perhaps?) onto the session.
* Return some error-related result code (INPUT works fine, too)
* Map that result code back to the action that shows the form. I'd
recommend using a redirect (not chaining, if you chain then there's no
need to use the session to preserve the data between actions, but
chaining is evil :-).
Then in your action that shows the form...
* retrieve the "new car info" data structure from the session, if it exists
* make that NewCar object available to your view via a getter
So your "ShowNewCarForm" is really an action that knows how to deal with
two cases:
1) This is the first time the user is seeing the form, the NewCar
datastructure is empty
2) The user is seeing this form after a processing attempt has failed,
the NewCar datastructure is on the session, you retrieve it an make it
available to the view via the getter.
If you you want to get fancier with preserving the NewCar data between
the "show" and the "process" actions you can look at the scope plug-in
(and flash scope, I believe). But storing/retrieving to/from the
session by hand is probably easier in this case.
And if you want to get fancier with the error data you preserve (like if
you want additional error messages to come back to the view action along
with the NewCar data) then you can take a look at the MessageStore
interceptor. It allows you to add ActionErrors or FieldErrors in the
processing action and have them available in the "view" action.
- Gary
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]