tomcat7 + struts2でwebアプリケーション(5) フォームとアクション(2)
アクションクラスのオブジェクトが持つメンバに値を渡す。
(1)アクションクラスにアクセサを追加
import com.opensymphony.xwork2.ActionSupport; public class TestAction extends ActionSupport { private InputModel model = new InputModel(); @Override public String execute() throws Exception { return "success"; } public InputModel getModel() { return model; } public void setModel(InputModel model) { this.model = model; } }
(2)フォームページで名前に”オブジェクト名.メンバ名”を設定する。(formTest.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <s:form action="testAction"> <s:textfield name="model.username" label="名前"/> <s:textfield name="model.password" label="パス"/> <s:submit value="送信"/> </s:form> </body> </html>
(3)結果ページで”オブジェクト名.メンバ名"でオブジェクトのメンバを参照するように変更する。(result.jsp)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>result</title> </head> <body> 名前:<s:property value="model.username"/> <br/> パス:<s:property value="model.password"/> </body> </html>