'2012.03.23 追記
このブログで扱っているSpringMVCのバージョンは2.5で、情報が古くなっています。
現状、アノテーションを使用してかなり柔軟で使いやすくなっています。
この記事を削除することはしませんが、最新の情報を検索されることをお勧めします。
-------------------------
さて、ここでは基本的なSpring MVCの使用方法を見てみましょう!
もしSpringのweb.xmlなどの基本的な設定方法が分からない場合は以下を参照してください。
パラメタの文字コードの設定もしています。
SpringMVCのControllerは複数存在します。UrlFilenameViewControllerは上の記事で使用しているので、ここではAbstractCommandControllerを継承して自作のControllerを作ります。
※通常Spring MVCでWEBを作る場合、SimpleFormControllerクラスを継承します。
下記の例はSimpleFormControllerを使用すればコードを書く必要はないのですが、
コードを書く必要がないということは動きが見えにくくなるかと思います。
それで記事として、原始人のようなAbstractCommandControllerクラスを使用することにしました。
【Controllerクラス】
package presentation; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractCommandController; import business.domain.CmdTest; public class CmdTestController extends AbstractCommandController { @Override protected ModelAndView handle(HttpServletRequest req, HttpServletResponse res, Object obj, BindException bind) throws Exception { //モデルクラス(データクラス) CmdTest cmd = (CmdTest)obj; //ビューとデータ ModelAndView modelAndView = new ModelAndView("/WEB-INF/jsp/cmdTest.jsp"); modelAndView.addObject("cmd", cmd); return modelAndView; } }
【モデル】
モデルクラス(POJO)です。
WEBから受け取ったパラメタの値を代入します。
StrutsでいうとActionFormに当たりますが、StrutsのようにActionFormを継承する必要がなく、フレームワークにデータクラスがが汚されないのが特徴です。
AbstractCommandControllerが画面のパラメタから自動でこのモデルクラスを作成してくれます。
とっても便利。
このあたりもStrutsのActionFormと同じです。ただしSpringの場合、パラメタとActionFormの関係をわざわざ設定ファイルに記述する必要がありません。
package business.domain; public class CmdTest { private boolean display = false; private String message; public boolean isDisplay() { return display; } public void setDisplay(boolean display) { this.display = display; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
【test-servlet.xmlの設定ファイル】
Springの設定ファイルです。
Controllerの設定とは別の設定も一応記述しています。
今回はControllerの設定のところだけ確認してもらえればと思います。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans
"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
"
xmlns:aop="http://www.springframework.org/schema/aop
"
xmlns:tx="http://www.springframework.org/schema/tx
"
xmlns:util="http://www.springframework.org/schema/util
"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
">
<!--
メッセージリソースの設定。
bean名はmessageSourceにする必要があります。
-->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
<!-- HandlerMapping -->
<bean id="handlerMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/input.html">fileNameController</prop>
<prop key="/cmdTest.html">cmdTestController</prop>
</props>
</property>
</bean>
<!-- JSP表示用のController
コントローラは、xxx-servlet.xmlに記述しないと、メッセージリソースのLocaleが設定されない。
つまり、日本語と判定してくれず、messages_ja.propertiesファイルを参照してくれない。
-->
<bean id="fileNameController" class="org.springframework.web.servlet.mvc.UrlFilenameViewController">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 継承した自作Controller -->
<bean id="cmdTestController" class="presentation.CmdTestController">
<property name="commandClass" value="business.domain.CmdTest" />
</bean>
</beans>
【JSP入力ファイル(/WEB-INF/jsp/input.jsp)】
<%@ page language="java" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%
>
<!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>入力テスト</title>
</head>
<body>
CmdControllerテスト<br>
<form action="cmdTest.html" method="post">
<input type="checkbox" name="display" value="true">メッセージを表示します<br>
<input type="text" name="message">
<input type="submit" value="入力">
</form>
</body>
</html>
【JSP結果ファイル(/WEB-INF/jsp/cmdTest.jsp)】
<%@ page language="java" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%
>
<!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>入力テスト</title>
</head>
<body>
CmdControllerテスト<br>
表示がTRUEのときにメッセージを表示します。<br>
<br>
<c:if test="${cmd.display}">
メッセージ:<c:out value="${cmd.message}"/>
</c:if>
</body>
</html>
【画面】
画面を表示するには、以下のURLをアクセスします。
プロジェクト名などが違う場合は、合わせてtestの部分を書き換えてアクセスしてください。
http://localhost:8080/test/input.html
【説明】
動作としては、チェックボックスをチェックするとテキストに入力した値を表示するという簡単なものです。
見るべきところは、入力画面からモデルオブジェクトに値を入れるところです。
まずtest-servlet.xmlファイルの以下の場所を見てください。
<bean id="cmdTestController" class="presentation.CmdTestController">
<property name="commandClass" value="business.domain.CmdTest" />
</bean>
commandClassプロパティに、モデルのクラス名を設定しています。
これはAbstractCommandControllerが持っているプロパティと機能です。
ここで設定したクラスを生成してパラメタの値を設定します。
ただし、パラメタ名とモデル(CmdTest)のクラスのgetter名はあわせておく必要があります。
次に見るべきは、CmdTestController クラスです。
handleメソッドを見てください。
Objectが引数になっています。
これが生成されたモデルクラスです!
//モデルクラス(データクラス)
CmdTest cmd = (CmdTest)obj;
のようにキャストするだけでモデルを使用することができます。
簡単ですよね!
【Spring MVCの使い方】
使い方の基本は以上のとおりです。
つまり、以下の感じです。
①Springで用意しているControllerクラスをそのまま使用する。
(上記では、UrlFilenameViewControllerクラス)
②Springで用意しているControllerクラスを継承して使用する。
(上記では、CmdTestController)
③SpringのControllerインターフェースをimplementsして完全に自作する。
ここでは紹介していませんし、めったにはやらないのですが完全自作してもよいのです!
Strutsでは、ActionやActionFormをextendsしないといけない制約があります。
Javaでは複数のクラスをextendsすることができないのでこれは再利用性などを考えるとそこそこ強い制約です。
Springではそのようなことがないのが特徴です。
いいですよね!Spring!
【補足】
ここでは妥当性チェック機能はつけていません。
これもStrutsと同じように設定ファイルに記述するだけで可能になります。
興味のある方は、別の記事に記載予定ですので、それを参照ください。
また、今回はパラメタとモデルを結びつけましたが、実はDate型はそのままでは結び付けられません。
結びつけの方法は別の記事で見ていこうと思います。
参考:
・SpringMVCを使用してWEBを作るには? (実践編)
・Controller内でApplicationContextを取得するには?