Click + Pico

シンプルがモットーなのにSpringとはこれいかに…ってことで、PageをPicoContainerで取り出せるように、ClickServletを拡張。

サーブレットがこんな感じ。


public class PicoClickServlet extends ClickServlet {

protected void handleRequest(HttpServletRequest request, HttpServletResponse response, boolean isPost) {
MutablePicoContainer container = new DefaultPicoContainer();
request.setAttribute("container", container);

begin(container);

try {
super.handleRequest(request, response, isPost);
} finally {
end(container);
}
}

private void begin(MutablePicoContainer container) {
RubbishDatabase dbh = new RubbishDatabase();
dbh.setLogging(true);
dbh.connect("jdbc:h2:file:" + getServletContext().getRealPath("/WEB-INF/dat/crd"), "sa", "");
container.registerComponentInstance(dbh);
}

private void end(MutablePicoContainer container) {
RubbishDatabase dbh = (RubbishDatabase) container.getComponentInstanceOfType(RubbishDatabase.class);
dbh.disconnect();
}

protected Page newPageInstance(String path, Class pageClass, HttpServletRequest request) throws Exception {
MutablePicoContainer container = (MutablePicoContainer) request.getAttribute("container");
container.registerComponentImplementation(pageClass);
return (Page) container.getComponentInstanceOfType(Page.class);
}

}

Pageがこんな感じ。


public class Foo extends Page {

private Table table = new Table("table");

private Database dbh = null;

public Foo(Database dbh) {
this.dbh = dbh;

table.setAttribute("class", "simple");
table.addColumn(new Column(Book.TITLE.getName().toLowerCase(), "タイトル"));
table.addColumn(new Column(Book.AUTHOR.getName().toLowerCase(), "著者"));
addControl(table);
}

public void onRender() {
table.setRowList(Arrays.asList(Book.findAny(dbh)));
}

}

間抜けコードだなぁ…。