0

我正在编写一些 Struts2 Rest 控制器,似乎 show() 和 view() 方法将返回两种不同类型的模型。由于需要键入实现 ModelDriven,因此我一直将类型设置为<Object>. 似乎有更好的方法来做到这一点。这是一些伪代码来演示我的问题。

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;
    }
}

请注意,有两种不同的类型要建模,因此ModelDriven<Object>必须使用。

4

2 回答 2

0

我以这种方式使用它,我也在互联网上的一些示例中找到了它。这主要是对您的方法的外观改变。

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;
    }

}
于 2013-12-08T04:22:40.180 回答
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.

于 2013-06-04T15:30:00.127 回答