javastrutsxdoclet

How to setup a Struts form with a recursive class member


I'm finding an issue when setting up a Struts form for a class containing a member reference to the same class.

class ExampleBean {
  Integer id;
  String name;
  ExampleBean parent;

  // Constructors, getters, setters
}

When accessing the webpage containing the form, it seems the process gets into an infinite loop, till it returns an exception.

I'm using xdoclet to generate the form, if that is of any help.


Solution

  • You are not providing enough information (so I can only guess what's happening) but I don't think this is a problem with Struts.

    When you use nested properties in your Struts form, you specify something like this for your HTML input names: parent.id and parent.name.

    When Struts find this during populating your action form with request data, it tries to do getParent().setId(...) and getParent().setName(...) on your form.

    If getParent() returns null, you will get an error from BeanUtils, something like java.lang.IllegalArgumentException: No bean specified. So in order for the inner bean binding to work you have to initialize it and then let Struts do the binding.

    By any chance did you do something like this:

    class ExampleBean {
      Integer id;
      String name;
      ExampleBean parent = new ExampleBean();
    
      // Constructors, getters, setters
    }
    

    because that will indeed cause an infinite recursion and a StackOverflowError when the JVM tries to create an instance.

    You should really show the complete code you are using!

    For situations like this, the Struts form reset() method is the one to use. You don't provide default initialization in the inner property of the bean, but instead you create the inner bean and initialize it in the outer bean inside the reset() method.