Struts2最小構成サンプルにAction追加
struts.xmlにアクションを追加
helloアクションに対応するActionクラスとメソッドを指定する。
<action name="hello" class="jp.hateblo.eichisanden.struts2.actions.HelloAction" method="hello"> <result name="success">/hello.jsp</result> </action>
HelloActionクラスを追加
Pojoでも良いらしいが、普通はActionSupportを継承するらしい。
struts.xmlに指定したhelloメソッドと、後で使うgetMessageメソッドを追加。
strutsのActionとActionFormがまとまった感じだが、仕事で使うときはActionに直接setter/getterを並べたら大変なことになりそう。
たぶん、データは外だしのクラスにするかな。
package jp.hateblo.eichisanden.struts2.actions; import com.opensymphony.xwork2.ActionSupport; public class HelloAction extends ActionSupport { private static final long serialVersionUID = 1L; private String message; public void setMessage(String message) { this.message = message; } public String getMessage() { return this.message; } public String hello() { setMessage("Hello World From Action"); LOG.debug("HelloAction : #0", getMessage()); return SUCCESS; } }
hello.jsp
propertyタグのvalueに"message"を指定すると、ActionのgetMessage()から値を取れる。
hoge.messageのように指定すれば、ActionのgetHoge()から取得したクラスのgetMessage()から値を取れるようだ。
<%@ page language="java" contentType="text/html; charset=windows-31j" pageEncoding="windows-31j"%> <%@ 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=windows-31j"> <title>Insert title here</title> </head> <body> <h1> <s:property value="message"/> </h1> </body> </html>
index.jsp
index.jspにhello.actionへのリンクを追加
<%@ page language="java" contentType="text/html; charset=windows-31j" pageEncoding="windows-31j"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-31j"> <title>Insert title here</title> </head> <body> <a href="<s:url action='/hello' />">Hello World</a> <br> <s:debug></s:debug> </body> </html>