Search code examples
javainheritancestruts2drypost-redirect-get

Struts2 Dynamic Form Flow


I am a struts 2 newbie, and I'm running into what seems like a structural issue. I'm assuming I'm missing something obvious, but not sure what.

I have a multi-page form, in which some of the form elements are dynamically generated, and the data is pre-filled from a database and / or session. The flow works like this:

  • Action1 SUCCESS loads Form1 ->
  • Form1 posts to Action2 ->
  • Action2 SUCCESS loads Form2, but Action2 INPUT reloads Form1

Form 1 elements are dynamic, so a database and / or session call and some prep is needed to build the form. Action2 doesn't know exactly what the form elements will be when it runs.

My problem is that I can't seem to avoid having all the Action1 execute code AGAIN in Action2's validate method. i.e., if the Action2 validate fails, Action2 needs to rerun all the code to build Form1.

If I do a redirectAction on an INPUT result (back to Action1), I lose all the error messages from the validate method.

I'm trying to figure out a way to avoid having all my setup code in two different places for every dynamic form I have. Any help would be greatly appreciated.


Solution

  • Boiling the question down to:

    how can I avoid duplicate code needed by both Action1 and Action2

    The main ways to follow DRY are:

    1. Create both the actions with two action methods inside a single Java file, and call a method (either custom or prepare()) from within (or before) each Action method.

    2. Create a BaseAction with a method (either custom or prepare()) and call it from within (or before) each Action extending it.

    3. Use a RedirectAction result when returning an INPUT result, with PRG pattern and MessageStore Interceptor to preserve messages.

    The links above are SO answers, potentially more helpful to new users than the (often cryptic) docs.