From Ruby to Java
本当は、Rails風にしようと思ったわけではなく、ふたがわさんがCubbyがいいっていってたので、インスパイヤされて作ったらRails風になっちゃったって感じ。
http://locahost:8080/sa-struts-tutorial/loginにアクセスすると、tutorial.action.LoginAction#index()が呼び出されます。
index()の戻り値がlogin.jspだと、/login/login.jspにフォワードされます。
また、/employee/list.jspが表示されているときにリンクタグが
<a href="edit/${e.id}">...</a>だと、/employee/edit/idの値に遷移し、idがActionにセットされ、edit()が呼び出されます。
edit()は以下のとおり。
URLのidの部分がアクションのidプロパティに設定されます。
@Execute(urlPattern = "edit/{id}")
public String edit() {
return "edit.jsp";
}
最初は、Rais風の1ユースケース、1アクションだと、アクションがごたごたするかと思ったんですが、そんなことないですね。Employeeテーブルをメンテナンスするアクションだってこんなにシンプルですから。
BeansとS2JDBCを使うとあんましコード書く必要ないしね。
URLがきれいだとやっぱ気持ちがいい。RESTfulまではこだわらなくてもいいかな。
これまで、難しく考えすぎてた気がする。ActionとEntityだけで十分に開発できるもの。
public class EmployeeAction {@Required
@IntegerType
public String id;@Required
public String name;@Required
public String jobType;@IntegerType
public String salary;@IntegerType
public String departmentId;@Required
@IntegerType
public String version;public List
empItems; public List
deptItems; public JdbcManager jdbcManager;
@Execute(validator = false)
public String index() {
empItems = jdbcManager
.from(Employee.class)
.orderBy("id")
.getResultList();
return "list.jsp";
}@Execute(validator = false, urlPattern = "edit/{id}")
public String edit() {
Employee emp = jdbcManager
.from(Employee.class)
.id(id)
.getSingleResult();
Beans.copy(emp, this).execute();
deptItems = jdbcManager
.from(Department.class)
.orderBy("id")
.getResultList();
return "edit.jsp";
}@Execute(input = "backToEdit")
public String confirm() {
return "confirm.jsp";
}@Execute(input = "confirm.jsp")
public String store() {
Employee emp = Beans.createAndCopy(Employee.class,
this).execute();
jdbcManager.update(emp).execute();
return index();
}@Execute(validator = false)
public String backToEdit() {
deptItems = jdbcManager
.from(Department.class)
.orderBy("id")
.getResultList();
return "edit.jsp";
}
}
HTMLのエスケープもRails風にこんな感じでできるようにしました。
タイトルに深い意味はないけど(笑)、Railsから移行するのは簡単だと思う。
${f:h(name)}
追記:
Strutsにこだわりのない方なら、Cubbyはすごくお勧めです。Struts抜きで自由にWebフレームワークを作ってもいいといわれたら、Cubbyみたいなやつを作りたかった気がする。