0

I am writing a few Struts2 Rest controllers and it seems that the show() and view() method will be returning two different types of models. Since implementing ModelDriven needs to be typed, I have been setting the type to <Object>. It seems like there is a better way to do this. Here is a bit of pseudo-code to demonstrate my issue.

public class SomeController implements ModelDriven<Object> {
    Object model;

    public HttpHeaders show() {
        // return a single item from the index() list
        model = new SingleItem();
    }

    public HttpHeaders index() {
        // return a list of all items
        model = new List<SingleItem>();
    }

    public Object getModel() {
        return model;
    }
}

Notice that there are two different types to model, and therefore ModelDriven<Object> must be used.

Andrea Ligios
  • 49,480
  • 26
  • 114
  • 243
hsoj48
  • 36
  • 4

2 Answers2

0

There's not a better way to do it; what else would you do?

I suppose you could create a model-specific Pair or a single/list composite and use the appropriate value/field in your results, but I'm not really sure you gain much by doing so.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
0

I use it in this fashion, which I also found in a few examples on the internet. It is mostly a cosmetic change to your approach.

public class FoldersController implements ModelDriven<Object>{
    private Folder model = new Folder();
    private Collection<JSONFolder> list;

    public HttpHeaders index() {
        list = fileService.getBaseFolders();
        return new DefaultHttpHeaders("index").disableCaching();
    }

    public HttpHeaders show() {
        model = fileService.getFolder();
        return new DefaultHttpHeaders("index").disableCaching();
    }

    @Override
    public Object getModel() {
        return (list != null ? list : model);
    }
    public void setModel(Folder model) {
        this.model = model;
    }

}
Manu
  • 609
  • 8
  • 18