tomcat7 + struts2でwebアプリ(2) フォームとアクション

テキスト入力フィールドに入力された文字を送信すると、
結果画面で入力された文字を表示するサンプル。


(1)struts.xmlにアクション定義を追加。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
    "http://struts.apache.org/dtds/struts-2.1.7.dtd">

<struts>
    <constant name="struts.devMode" value="false" />

    <package name="myapp" extends="struts-default" namespace="/">
    	<action name="testAction" class="TestAction">
    		<result name="success">/result.jsp</result>
    	</action>
    </package>

</struts>

(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="username" 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="username"/>

</body>
</html>

(4)アクションを作成(TestAction.java)
フォームからの入力を受け取って、遷移先の画面に渡すのアクションだけです。

import com.opensymphony.xwork2.ActionSupport;


public class TestAction extends ActionSupport {
	private String username;

	@Override
	public String execute() throws Exception {
		return "success";
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

}

このアクション記述だと、入力要素数に応じてメンバが必要になる。