Springmvc-quick-guide
Spring-MVCフレームワークの概要
Spring Web MVCフレームワークは、モデルビューコントローラーアーキテクチャと、柔軟で疎結合のWebアプリケーションを開発するために使用できる既製のコンポーネントを提供します。 MVCパターンにより、アプリケーションのさまざまな側面(入力ロジック、ビジネスロジック、およびUIロジック)が分離され、これらの要素間の疎結合が提供されます。
- Model はアプリケーションデータをカプセル化し、一般に POJO で構成されます。
- View はモデルデータのレンダリングを担当し、一般に、クライアントのブラウザーが解釈できる HTML 出力を生成します。
- Controller は、 User Requests および Building Appropriate Model を処理し、レンダリングのためにビューに渡します。
DispatcherServlet
Spring Webモデルビューコントローラー(MVC)フレームワークは、すべてのHTTP要求と応答を処理するDispatcherServletを中心に設計されています。 次の図に、Spring Web MVC DispatcherServletのリクエスト処理ワークフローを示します。
以下は、DispatcherServletへの着信HTTP要求に対応する一連のイベントです-
- HTTPリクエストを受信した後、DispatcherServletは HandlerMapping を参照して適切なコントローラーを呼び出します。
- コントローラーは要求を受け取り、使用されている GET または* POSTメソッド*に基づいて適切なサービスメソッドを呼び出します。 サービスメソッドは、定義されたビジネスロジックに基づいてモデルデータを設定し、ビュー名をDispatcherServletに返します。
- DispatcherServletは、 ViewResolver のヘルプを利用して、リクエストに対して定義されたビューを取得します。
- ビューが完成すると、DispatcherServletはモデルデータをブラウザに渡し、最終的にレンダリングされます。
上記のすべてのコンポーネント、つまり HandlerMapping、Controller、およびViewResolverは WebApplicationContext の一部です。これは、Webアプリケーションに必要な追加機能を備えたプレーンな ApplicationContext の拡張です。
必要な構成
*web.xml* ファイルでURLマッピングを使用して、DispatcherServletで処理するリクエストをマッピングする必要があります。 以下は、 *HelloWeb* DispatcherServletの宣言とマッピングを示す例です-
<web-app id = "WebApp_ID" version = "2.4"
xmlns = "http://java.sun.com/xml/ns/j2ee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
</web-app>
*web.xml* ファイルは、Webアプリケーションの *WebContent/WEB-INF* ディレクトリに保存されます。 *HelloWeb* DispatcherServletの初期化時に、フレームワークは、アプリケーションのWebContent/WEB-INFディレクトリにある *[servlet-name] -servlet.xml* という名前のファイルからアプリケーションコンテキストをロードしようとします。 この場合、ファイルは *HelloWeb-servlet.xml* になります。
次に、 <servlet-mapping> タグは、どのDispatcherServletによってどのURLが処理されるかを示します。 ここでは、.jspで終わるすべてのHTTP要求が HelloWeb DispatcherServletによって処理されます。
デフォルトのファイル名を [servlet-name] -servlet.xml に、デフォルトの場所をWebContent/WEB-INFにしたくない場合は、サーブレットリスナー ContextLoaderListener を追加して、このファイル名と場所をカスタマイズできます。次のようにweb.xmlファイル-
<web-app...>
<!-------- DispatcherServlet definition goes here----->
....
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/HelloWeb-servlet.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
</web-app>
次に、WebアプリケーションのWebContent/WEB-INFディレクトリに配置されている HelloWeb-servlet.xml ファイルに必要な構成を確認します。
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.finddevguides"/>
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
</beans>
以下は HelloWeb-servlet.xml ファイルに関するいくつかの重要なポイントです-
- [servlet-name] -servlet.xml ファイルは、定義されたBeanを作成するために使用され、グローバルスコープで同じ名前で定義されたBeanの定義をオーバーライドします。
- <context:component-scan …> タグは、Spring MVCアノテーションスキャン機能を有効にするために使用されます。これにより、 @ Controller や @ RequestMapping などのアノテーションを使用できます。
- InternalResourceViewResolver には、ビュー名を解決するために定義されたルールがあります。 上記のルールに従って、 hello という名前の論理ビューは、 /WEB-INF/jsp/hello.jsp にあるビュー実装に委任されます。
ここで、実際のコンポーネント(コントローラー、モデル、ビュー)の作成方法を理解しましょう。
コントローラーの定義
DispatcherServletは、要求をコントローラーに委任して、固有の機能を実行します。 @ Controller 注釈は、特定のクラスがコントローラーの役割を果たしていることを示します。 @ RequestMapping 注釈は、URLをクラス全体または特定のハンドラーメソッドにマップするために使用されます。
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
*@ Controller* アノテーションは、クラスをSpring MVCコントローラーとして定義します。 ここで、 *@ RequestMapping* の最初の使用法は、このコントローラーのすべての処理メソッドが */hello* パスに関連していることを示しています。
次の注釈* @ RequestMapping(method = RequestMethod.GET)は、 printHello()*メソッドを、HTTP GET要求を処理するコントローラーのデフォルトのサービスメソッドとして宣言するために使用されます。 同じURLでPOST要求を処理する別のメソッドを定義できます。
上記のコントローラーを別の形式で記述することもできます。この場合、次のように@RequestMappingに追加の属性を追加できます-
@Controller
public class HelloController{
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
*value* 属性は、ハンドラーメソッドがマップされるURLを示し、 *method* 属性は、HTTP GET要求を処理するサービスメソッドを定義します。
以下は、上記で定義したコントローラーに関して注意すべき重要な点です-
- サービスメソッド内で必要なビジネスロジックを定義します。 要件に従って、このメソッド内で別のメソッドを呼び出すことができます。
- 定義されたビジネスロジックに基づいて、このメソッド内でモデルを作成します。 さまざまなモデル属性を設定できます。これらの属性は、結果を表示するためにビューからアクセスされます。 この例では、属性「message」でモデルを作成します。
- 定義されたサービスメソッドは、モデルのレンダリングに使用される view の名前を含む文字列を返すことができます。 この例では、論理ビュー名として「hello」を返します。
JSPビューの作成
Spring MVCは、さまざまなプレゼンテーションテクノロジーの多くのタイプのビューをサポートしています。 これらには、 JSP、HTML、PDF、Excelワークシート、XML、Velocityテンプレート、XSLT、JSON、Atom および RSS フィード、 JasperReports などが含まれます。 ただし、最も一般的なものは、JSTLで記述されたJSPテンプレートです。 そこで、/WEB-INF/hello/hello.jspに簡単なhelloビューを記述しましょう-
<html>
<head>
<title>Hello Spring MVC</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
ここ $ \ {message} ここに属性があり、Controller内で設定します。 ビュー内に表示される複数の属性を持つことができます。
Spring MVC-環境設定
この章では、Spring Frameworkで作業を開始するための開発環境を準備する方法について説明します。 この章では、Spring Frameworkをセットアップする前に、マシンで JDK、Tomcat 、および Eclipse をセットアップする方法も説明します-
ステップ1-Java Development Kit(JDK)のセットアップ
最新バージョンは、OracleのJavaサイト-https://www.oracle.com/technetwork/java/javase/downloads/indexl[Java SE Downloads]からダウンロードできます。 ダウンロードしたファイルにJDKをインストールする手順があります。指定された手順に従ってセットアップをインストールおよび構成します。 セットアップが完了したら、PATHおよびJAVA_HOME環境変数を設定して、* java および *javac (通常はそれぞれ java_install_dir/bin および java_install_dir )を含むディレクトリを参照するようにします。
Windowsを実行していて、JDKを C:\ jdk1.6.0_15 にインストールした場合、* C:\ autoexec.batファイル*に次の行を追加する必要があります。
set PATH = C:\jdk1.6.0_15\bin;%PATH%
set JAVA_HOME = C:\jdk1.6.0_15
または、Windows NT/2000/XPでは、マイコンピュータを右クリックして、プロパティ→詳細設定→環境変数を選択することもできます。 次に、PATH値を更新し、[OK]ボタンをクリックします。
UNIX(Solaris、Linuxなど)で、SDKが /usr/local/jdk1.6.0_15 にインストールされ、Cシェルを使用する場合、次のコマンドを .cshrc にキー入力する必要があります。ファイル。
setenv PATH/usr/local/jdk1.6.0_15/bin:$PATH
setenv JAVA_HOME/usr/local/jdk1.6.0_15
または、 Borland JBuilder、Eclipse、IntelliJ IDEA 、または Sun ONE Studio などの統合開発環境(IDE)を使用する場合は、単純なプログラムをコンパイルおよび実行して、IDEがJavaのインストール先を認識していることを確認します。 IDEのドキュメントに記載されているセットアップ。
ステップ2-Apache Common Logging APIをインストールする
Apache Commons Logging APIの最新バージョンは、https://commons.apache.org/logging/download_logging.cgi [https://commons.apache.org/logging/]からダウンロードできます。 インストールをダウンロードしたら、バイナリ配布物を便利な場所に解凍します。
たとえば、WindowsではC:\ commons-logging-1.1.1、Linux/Unixでは/usr/local/commons-logging1.1.1です。 このディレクトリには、次のjarファイルやその他のサポートドキュメントなどが含まれます。
このディレクトリでCLASSPATH変数を適切に設定してください。そうしないと、アプリケーションの実行中に問題が発生します。
ステップ3-Eclipse IDEのセットアップ
このチュートリアルのすべての例は、Eclipse IDEを使用して作成されています。 したがって、最新バージョンのEclipseをマシンにインストールすることをお勧めします。
Eclipse IDEをインストールするには、次のリンクhttps://www.eclipse.org/downloads/から最新のEclipseバイナリをダウンロードします。 インストールがダウンロードされたら、バイナリ配布物を便利な場所に解凍します。
たとえば、WindowsではC:\ eclipse、Linux/Unixでは/usr/local/eclipseで、最後にPATH変数を適切に設定します。
Eclipseは、Windowsマシンで次のコマンドを実行することで開始できます。または、eclipse.exeをダブルクリックするだけです。
%C:\eclipse\eclipse.exe
Eclipseは、UNIX(Solaris、Linuxなど)マシンで次のコマンドを実行することで起動できます-
$/usr/local/eclipse/eclipse
正常に起動した後、すべてが正常であれば、次の画面が表示されます。
ステップ4-Spring Frameworkライブラリのセットアップ
これで問題がなければ、Spring Frameworkのセットアップに進むことができます。 以下は、フレームワークをマシンにダウンロードしてインストールする手順です。
- SpringをWindowsにインストールするかUNIXにインストールするかを選択してから、次のステップに進み、Windowsの場合は* .zipファイル*、Unixの場合は .tz ファイルをダウンロードします。
- [[1]]
- Windowsマシンに spring-framework-4.3.1.RELEASE-dist.zip をダウンロードしました。ダウンロードしたファイルを解凍すると、次のようにE:\ spring内のディレクトリ構造が得られます。
すべてのSpringライブラリは、ディレクトリ E:\ spring \ libs にあります。 このディレクトリでCLASSPATH変数を適切に設定してください。そうしないと、アプリケーションの実行中に問題が発生します。 Eclipseを使用する場合、すべての設定はEclipseを介して行われるため、CLASSPATHを設定する必要はありません。
この最後の手順を完了すると、次の章で説明する最初のSpringの例に進む準備が整います。
Spring MVC-Hello Worldの例
次の例は、Spring MVCフレームワークを使用して、単純なWebベースの Hello World アプリケーションを作成する方法を示しています。 まず、動作するEclipse IDEを用意し、以降の手順に従って、Spring Web Frameworkを使用して動的Webアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a Dynamic Web Project with a name *HelloWeb *and create a package com.finddevguides under the src folder in the created project. |
2 | Drag and drop the following Spring and other libraries into the folder* WebContent/WEB-INF/lib*.. |
3 | Create a Java class *HelloController *under the com.finddevguides package. |
4 | Create Spring configuration* files web.xml and HelloWeb-servlet.xml *under the WebContent/WEB-INF folder. |
5 | Create a sub-folder with a name* jsp under the WebContent/WEB-INFfolder. Create a view file hello.jsp* under this sub-folder. |
6 | The final step is to create the content of the source and configuration files and export the application as explained below. |
HelloController.java
package com.finddevguides;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
web.xml
<web-app id = "WebApp_ID" version = "2.4"
xmlns = "http://java.sun.com/xml/ns/j2ee"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
HelloWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.finddevguides"/>
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
</beans>
hello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
以下は、Webアプリケーションに含まれるSpringおよびその他のライブラリのリストです。 これらのファイルをドラッグして、 WebContent/WEB-INF/lib フォルダーにドロップするだけです。
- servlet-api-x.y.z.jar
- commons-logging-x.y.z.jar
- spring-aop-x.y.z.jar
- spring-beans-x.y.z.jar
- spring-context-x.y.z.jar
- spring-core-x.y.z.jar
- spring-expression-x.y.z.jar
- spring-webmvc-x.y.z.jar
- spring-web-x.y.z.jar
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、エクスポート→WARファイル*オプションを使用して、 *HelloWeb.war ファイルをTomcatの webapps フォルダーに保存します。
Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 ここで、URL- http://localhost:8080/HelloWeb/hello にアクセスしてみてください。 Spring Webアプリケーションですべてが問題なければ、次の画面が表示されます。
指定されたURLで、 HelloWeb はアプリケーション名であり、helloは@RequestMapping( "/hello")を使用してコントローラーで言及した仮想サブフォルダーであることに注意してください。 * @ RequestMapping( "/")を使用してURLをマッピングするときに直接ルートを使用できます。この場合、短いURL *http://localhost:8080/HelloWeb/ を使用して同じページにアクセスできますが、異なるフォルダの下に異なる機能があります。
Spring MVC-フォーム処理の例
次の例は、Spring MVCフレームワークを使用して、単純なWebベースの Hello World アプリケーションを作成する方法を示しています。 まず、動作するEclipse IDEを用意し、以降の手順に従って、Spring Web Frameworkを使用して動的Webアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a project with a name HelloWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes Student, StudentController under the com.finddevguides package. |
3 | Create view files student.jsp, result.jsp under the jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
Student.java
package com.finddevguides;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
StudentController.java
package com.finddevguides;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class StudentController {
@RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("SpringWeb")Student student,
ModelMap model) {
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
ここでは、最初のサービスメソッド* student()*で、ModelAndViewオブジェクトに「command」という名前の空のStudentobjectを渡しました。 これは、JSPファイルで<form:form>タグを使用する場合、Springフレームワークが「コマンド」という名前のオブジェクトを予期するためです。 したがって、student()メソッドが呼び出されると、student.jspビューが返されます。
2番目のサービスメソッド* addStudent()*は、HelloWeb/addStudent URLのPOSTメソッドに対して呼び出されます。 送信された情報に基づいて、モデルオブジェクトを準備します。 最後に、サービスメソッドから「結果」ビューが返され、result.jspがレンダリングされます。
student.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method = "POST" action = "/HelloWeb/addStudent">
<table>
<tr>
<td><form:label path = "name">Name</form:label></td>
<td><form:input path = "name"/></td>
</tr>
<tr>
<td><form:label path = "age">Age</form:label></td>
<td><form:input path = "age"/></td>
</tr>
<tr>
<td><form:label path = "id">id</form:label></td>
<td><form:input path = "id"/></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
result.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、エクスポート→WARファイルオプションを使用して、 SpringWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 ここで、URL http://localhost:8080/SpringWeb/studentを試してください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
必要な情報を送信したら、送信ボタンをクリックしてフォームを送信します。 Spring Webアプリケーションで問題がなければ、次の画面が表示されます。
Spring MVC-ページリダイレクトの例
次の例は、リダイレクトを使用してhttp要求を別のページに転送する単純なWebベースのアプリケーションを作成する方法を示しています。 まず、作業中のEclipse IDEを用意し、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発するための次の手順を検討します。
Step | Description |
---|---|
1 | Create a project with a name HelloWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create a Java class WebController under the com.finddevguides package. |
3 | Create view files index.jsp, final.jsp under jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
WebController.java
package com.finddevguides;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class WebController {
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index() {
return "index";
}
@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public String redirect() {
return "redirect:finalPage";
}
@RequestMapping(value = "/finalPage", method = RequestMethod.GET)
public String finalPage() {
return "final";
}
}
次に、Springビューファイル index.jsp のコンテンツを示します。 これはランディングページになり、このページはアクセスリダイレクトサービスメソッドにリクエストを送信します。アクセスリダイレクトサービスメソッドはこのリクエストを別のサービスメソッドにリダイレクトし、最終的に* final.jsp *ページが表示されます。
index.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring Page Redirection</title>
</head>
<body>
<h2>Spring Page Redirection</h2>
<p>Click below button to redirect the result to new page</p>
<form:form method = "GET" action = "/HelloWeb/redirect">
<table>
<tr>
<td>
<input type = "submit" value = "Redirect Page"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
final.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring Page Redirection</title>
</head>
<body>
<h2>Redirected Page</h2>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、HelloWeb.warファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URL –http://localhost:8080/HelloWeb/indexを試してください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
「ページのリダイレクト」ボタンをクリックして、フォームを送信し、リダイレクトされた最終ページに移動します。 Spring Webアプリケーションで問題がなければ、次の画面が表示されるはずです-
Spring MVC-静的ページの例
次の例は、Spring MVC Frameworkを使用して簡単なWebベースのアプリケーションを作成する方法を示しています。SpringMVCフレームワークは、 <mvc:resources> タグを使用して、静的ページと動的ページにアクセスできます。
まず、動作するEclipse IDEを用意し、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発するための次の手順を順守します。
Step | Description |
---|---|
1 | Create a project with a name HelloWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create a Java class WebController under the com.finddevguides package. |
3 | Create a static file final under jsp sub-folder. |
4 | Update the Spring configuration file HelloWeb-servlet.xml under the WebContent/WEB-INF folder as shown below. |
5 | The final step is to create the content of the source and configuration files and export the application, which is explained below. |
WebController.java
package com.finddevguides;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class WebController {
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index() {
return "index";
}
@RequestMapping(value = "/staticPage", method = RequestMethod.GET)
public String redirect() {
return "redirect:/pages/final";
}
}
HelloWeb-servlet.xml
<?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:context = "http://www.springframework.org/schema/context"
xmlns:mvc = "http://www.springframework.org/schema/mvc"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.finddevguides"/>
<bean id = "viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<mvc:resources mapping = "/pages/**" location = "/WEB-INF/pages/"/>
<mvc:annotation-driven/>
</beans>
ここでは、 <mvc:resources …./> タグが静的ページのマッピングに使用されています。 マッピング属性は、httpリクエストのURLパターンを指定する* Antパターン*でなければなりません。 location属性は、画像、スタイルシート、JavaScript、その他の静的コンテンツを含む静的ページを持つ1つ以上の有効なリソースディレクトリの場所を指定する必要があります。 値のコンマ区切りリストを使用して、複数のリソースの場所を指定できます。
次に、Springビューファイル WEB-INF/jsp/index.jsp のコンテンツを示します。 これはランディングページになります。このページは* staticPageサービスメソッド*にアクセスするためのリクエストを送信し、WEB-INF/pagesフォルダーで利用可能な静的ページにこのリクエストをリダイレクトします。
index.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring Landing Page</title>
</head>
<body>
<h2>Spring Landing Pag</h2>
<p>Click below button to get a simple HTML page</p>
<form:form method = "GET" action = "/HelloWeb/staticPage">
<table>
<tr>
<td>
<input type = "submit" value = "Get HTML Page"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
最後の
<html>
<head>
<title>Spring Static Page</title>
</head>
<body>
<h2>A simple HTML page</h2>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、HelloWeb.warファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 次に、URL(http://localhost:8080/HelloWeb/index)にアクセスしてみます。 Spring Webアプリケーションですべてが問題なければ、次の画面が表示されます。
「Get HTML Page」ボタンをクリックして、staticPageサービスメソッドで言及されている静的ページにアクセスします。 Spring Webアプリケーションで問題がなければ、次の画面が表示されます。
Spring MVC-テキストボックスの例
次の例は、Spring Web MVCフレームワークを使用してフォームでテキストボックスを使用する方法を示しています。 まず、作業中のEclipse IDEを用意し、次の手順に従って、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a project with a name HelloWeb under a package com.finddevguides as explained in the Spring MVC - Hello World Example chapter. |
2 | Create a Java classes Student, StudentController under the com.finddevguides package. |
3 | Create a view files student.jsp, result.jsp under jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
Student.java
package com.finddevguides;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
StudentController.java
package com.finddevguides;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class StudentController {
@RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("SpringWeb")Student student,
ModelMap model) {
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
ここでは、最初のサービスメソッド* student()、ModelAndViewオブジェクトに空のStudentobjectを「command」という名前で渡しました。これは、 *<form:formを使用している場合、Springフレームワークは「command」 > JSPファイル内のタグ。 したがって、student()メソッドが呼び出されると、 student.jsp view が返されます。
2番目のサービスメソッド* addStudent()は、 *HelloWeb/addStudent URLのPOSTメソッドに対して呼び出されます。 送信された情報に基づいて、モデルオブジェクトを準備します。 最後に、サービスメソッドから「結果」ビューが返され、result.jspがレンダリングされます。
student.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method = "POST" action = "/HelloWeb/addStudent">
<table>
<tr>
<td><form:label path = "name">Name</form:label></td>
<td><form:input path = "name"/></td>
</tr>
<tr>
<td><form:label path = "age">Age</form:label></td>
<td><form:input path = "age"/></td>
</tr>
<tr>
<td><form:label path = "id">id</form:label></td>
<td><form:input path = "id"/></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
ここでは、 <form:input/> タグを使用してHTMLテキストボックスをレンダリングしています。 たとえば-
<form:input path = "name"/>
次のHTMLコンテンツをレンダリングします。
<input id = "name" name = "name" type = "text" value = ""/>
result.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 HelloWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLを試してください- http://localhost:8080/HelloWeb/student 。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
必要な情報を送信したら、送信ボタンをクリックしてフォームを送信します。 Spring Webアプリケーションで問題がなければ、次の画面が表示されます。
Spring MVC-パスワードの例
次の例では、Spring Web MVCフレームワークを使用してフォームでパスワードを使用する方法を説明します。 まず、動作するEclipse IDEを用意し、次の手順に従って、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a project with a name HelloWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes User, UserController under the com.finddevguidespackage. |
3 | Create view files user.jsp, users.jsp under jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.finddevguides;
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserController.java
package com.finddevguides;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user() {
return new ModelAndView("user", "command", new User());
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
return "users";
}
}
ここでは、最初のサービスメソッド* user()*で、ModelAndViewオブジェクトに「command」という名前の空のUserオブジェクトを渡しました。これは、<form:formを使用している場合、Springフレームワークが「command」 > JSPファイルのタグ。 そのため、user()メソッドが呼び出されると、user.jspビューが返されます。
2番目のサービスメソッド* addUser()*は、HelloWeb/addUser URLのPOSTメソッドに対して呼び出されます。 送信された情報に基づいて、モデルオブジェクトを準備します。 最後に、「users」ビューがサービスメソッドから返され、users.jspがレンダリングされます。
user.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "/HelloWeb/addUser">
<table>
<tr>
<td><form:label path = "username">User Name</form:label></td>
<td><form:input path = "username"/></td>
</tr>
<tr>
<td><form:label path = "password">Age</form:label></td>
<td><form:password path = "password"/></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
ここでは、<form:password/>タグを使用してHTMLパスワードボックスをレンダリングしています。 たとえば-
<form:password path = "password"/>
次のHTMLコンテンツをレンダリングします。
<input id = "password" name = "password" type = "password" value = ""/>
users.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
</table>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、HelloWeb.warファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URL –http://localhost:8080/HelloWeb/userを試してください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
必要な情報を送信したら、送信ボタンをクリックしてフォームを送信します。 Spring Webアプリケーションで問題がなければ、次の画面が表示されます。
Spring MVC-TextAreaの例
次の例では、Spring Web MVCフレームワークを使用してフォームでTextAreaを使用する方法を説明します。 まず、動作するEclipse IDEを用意し、以降の手順に従って、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a project with a name HelloWeb under a package com.finddevguides as explained in the Spring MVC − Hello World chapter. |
2 | Create Java classes User, UserController under the com.finddevguidespackage. |
3 | Create view files user.jsp, users.jsp under jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.finddevguides;
public class User {
private String username;
private String password;
private String address;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
UserController.java
package com.finddevguides;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user() {
return new ModelAndView("user", "command", new User());
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
return "users";
}
}
ここで、最初のサービスメソッドuser()に対して、ModelFormViewオブジェクトに「command」という名前の空のUserオブジェクトを渡しました。これは、<form:form>を使用している場合、Springフレームワークが「command」 JSPファイル内のタグ。 そのため、user()メソッドが呼び出されると、user.jspビューが返されます。
2番目のサービスメソッドaddUser()は、HelloWeb/addUser URLのPOSTメソッドに対して呼び出されます。 送信された情報に基づいて、モデルオブジェクトを準備します。 最後に、「users」ビューがサービスメソッドから返され、users.jspがレンダリングされます。
user.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "/HelloWeb/addUser">
<table>
<tr>
<td><form:label path = "username">User Name</form:label></td>
<td><form:input path = "username"/></td>
</tr>
<tr>
<td><form:label path = "password">Age</form:label></td>
<td><form:password path = "password"/></td>
</tr>
<tr>
<td><form:label path = "address">Address</form:label></td>
<td><form:textarea path = "address" rows = "5" cols = "30"/></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
ここでは、 <form:textarea/> タグを使用して、HTMLテキストエリアボックスをレンダリングしています。 たとえば-
<form:textarea path = "address" rows = "5" cols = "30"/>
次のHTMLコンテンツをレンダリングします。
<textarea id = "address" name = "address" rows = "5" cols = "30"></textarea>
users.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
<tr>
<td>Address</td>
<td>${address}</td>
</tr>
</table>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、HelloWeb.warファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URL –http://localhost:8080/HelloWeb/userを試してください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
必要な情報を送信したら、送信ボタンをクリックしてフォームを送信します。 Spring Webアプリケーションで問題がなければ、次の画面が表示されます。
Spring MVC-チェックボックスの例
次の例では、Spring Web MVCフレームワークを使用してフォームで単一チェックボックスを使用する方法について説明します。 まず、動作するEclipse IDEを用意し、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発するための次の手順を検討します。
Step | Description |
---|---|
1 | Create a project with a name HelloWeb under a package com.finddevguidesas explained in the Spring MVC - Hello World Example chapter. |
2 | Create Java classes User, UserController under the com.finddevguidespackage. |
3 | Create a view files user.jsp, users.jsp under jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.finddevguides;
public class User {
private String username;
private String password;
private String address;
private boolean receivePaper;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public boolean isReceivePaper() {
return receivePaper;
}
public void setReceivePaper(boolean receivePaper) {
this.receivePaper = receivePaper;
}
}
UserController.java
package com.finddevguides;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user() {
return new ModelAndView("user", "command", new User());
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
model.addAttribute("receivePaper", user.isReceivePaper());
return "users";
}
}
ここで、最初のサービスメソッドuser()に対して、ModelFormViewオブジェクトに「command」という名前の空のUserオブジェクトを渡しました。これは、<form:form>を使用している場合、Springフレームワークが「command」 JSPファイル内のタグ。 したがって、user()メソッドが呼び出されると、user.jspビューが返されます。
2番目のサービスメソッドaddUser()は、HelloWeb/addUser URLのPOSTメソッドに対して呼び出されます。 送信された情報に基づいて、モデルオブジェクトを準備します。 最後に、「users」ビューがサービスメソッドから返され、users.jspがレンダリングされます。
user.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "/HelloWeb/addUser">
<table>
<tr>
<td><form:label path = "username">User Name</form:label></td>
<td><form:input path = "username"/></td>
</tr>
<tr>
<td><form:label path = "password">Age</form:label></td>
<td><form:password path = "password"/></td>
</tr>
<tr>
<td><form:label path = "address">Address</form:label></td>
<td><form:textarea path = "address" rows = "5" cols = "30"/></td>
</tr>
<tr>
<td><form:label path = "receivePaper">Subscribe Newsletter</form:label></td>
<td><form:checkbox path = "receivePaper"/></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
ここでは、 <form:checkboxes/> タグを使用して、HTMLチェックボックスをレンダリングしています。
たとえば-
<form:checkbox path="receivePaper"/>
次のHTMLコンテンツをレンダリングします。
<input id="receivePaper1" name = "receivePaper" type = "checkbox" value = "true"/>
<input type = "hidden" name = "_receivePaper" value = "on"/>
users.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
<tr>
<td>Address</td>
<td>${address}</td>
</tr>
<tr>
<td>Subscribed to Newsletter</td>
<td>${receivePaper}</td>
</tr>
</table>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、HelloWeb.warファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLを試してください-http://localhost:8080/HelloWeb/user。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
必要な情報を送信したら、送信ボタンをクリックしてフォームを送信します。 Spring Webアプリケーションで問題がなければ、次の画面が表示されます。
Spring MVC-チェックボックスの例
次の例では、Spring Web MVCフレームワークを使用してフォームで複数のチェックボックスを使用する方法を説明します。 まず、動作するEclipse IDEを用意し、次の手順に従って、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a project with a name HelloWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes User, UserController under the com.finddevguidespackage. |
3 | Create view files user.jsp, users.jsp under the jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.finddevguides;
public class User {
private String username;
private String password;
private String address;
private boolean receivePaper;
private String [] favoriteFrameworks;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public boolean isReceivePaper() {
return receivePaper;
}
public void setReceivePaper(boolean receivePaper) {
this.receivePaper = receivePaper;
}
public String[] getFavoriteFrameworks() {
return favoriteFrameworks;
}
public void setFavoriteFrameworks(String[] favoriteFrameworks) {
this.favoriteFrameworks = favoriteFrameworks;
}
}
UserController.java
package com.finddevguides;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user() {
User user = new User();
user.setFavoriteFrameworks((new String []{"Spring MVC","Struts 2"}));
ModelAndView modelAndView = new ModelAndView("user", "command", user);
return modelAndView;
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
model.addAttribute("receivePaper", user.isReceivePaper());
model.addAttribute("favoriteFrameworks", user.getFavoriteFrameworks());
return "users";
}
@ModelAttribute("webFrameworkList")
public List<String> getWebFrameworkList() {
List<String> webFrameworkList = new ArrayList<String>();
webFrameworkList.add("Spring MVC");
webFrameworkList.add("Struts 1");
webFrameworkList.add("Struts 2");
webFrameworkList.add("Apache Wicket");
return webFrameworkList;
}
}
ここでは、最初のサービスメソッド* user()に対して、ModelAndViewオブジェクトに「command」という名前の空の *User オブジェクトを渡しました。これは、Springフレームワークが、<command JSPファイルのform:form>タグ。 したがって、* user()メソッドが呼び出されると、 *user.jsp ビューが返されます。
2番目のサービスメソッド* addUser()は、 *HelloWeb/addUser URLのPOSTメソッドに対して呼び出されます。 送信された情報に基づいて、モデルオブジェクトを準備します。 最後に、「users」ビューがサービスメソッドから返され、users.jspがレンダリングされます。
user.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "/HelloWeb/addUser">
<table>
<tr>
<td><form:label path = "username">User Name</form:label></td>
<td><form:input path = "username"/></td>
</tr>
<tr>
<td><form:label path = "password">Age</form:label></td>
<td><form:password path = "password"/></td>
</tr>
<tr>
<td><form:label path = "address">Address</form:label></td>
<td><form:textarea path = "address" rows = "5" cols = "30"/></td>
</tr>
<tr>
<td><form:label path = "receivePaper">Subscribe Newsletter</form:label></td>
<td><form:checkbox path = "receivePaper"/></td>
</tr>
<tr>
<td><form:label path = "favoriteFrameworks">Favorite Web Frameworks</form:label></td>
<td><form:checkboxes items = "${webFrameworkList}" path = "favoriteFrameworks"/></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
ここでは、 <form:checkboxes/> タグを使用してHTMLチェックボックスをレンダリングしています。
<form:checkboxes items = "${webFrameworkList}" path = "favoriteFrameworks"/>
次のHTMLコンテンツをレンダリングします。
<span>
<input id = "favoriteFrameworks1" name = "favoriteFrameworks" type = "checkbox" value = "Spring MVC" checked = "checked"/>
<label for = "favoriteFrameworks1">Spring MVC</label>
</span>
<span>
<input id = "favoriteFrameworks2" name = "favoriteFrameworks" type = "checkbox" value = "Struts 1"/>
<label for = "favoriteFrameworks2">Struts 1</label>
</span>
<span>
<input id = "favoriteFrameworks3" name = "favoriteFrameworks" type = "checkbox" value = "Struts 2" checked = "checked"/>
<label for = "favoriteFrameworks3">Struts 2</label>
</span>
<span>
<input id = "favoriteFrameworks4" name = "favoriteFrameworks" type = "checkbox" value = "Apache Wicket"/>
<label for = "favoriteFrameworks4">Apache Wicket</label>
</span>
<input type = "hidden" name = "_favoriteFrameworks" value = "on"/>
users.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
<tr>
<td>Address</td>
<td>${address}</td>
</tr>
<tr>
<td>Subscribed to Newsletter</td>
<td>${receivePaper}</td>
</tr>
<tr>
<td>Favorite Web Frameworks</td>
<td> <% String[] favoriteFrameworks = (String[])request.getAttribute("favoriteFrameworks");
for(String framework: favoriteFrameworks) {
out.println(framework);
}
%></td>
</tr>
</table>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、エクスポート→WARファイル*オプションを使用して、 *HelloWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URL http://localhost:8080/HelloWeb/user を試してください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
必要な情報を送信したら、送信ボタンをクリックしてフォームを送信します。 Spring Webアプリケーションに問題がなければ、次の画面が表示されます。
Spring MVC-RadioButtonの例
次の例は、Spring Web MVCフレームワークを使用してフォームでRadioButtonを使用する方法を示しています。 それを開始するには、作業中のEclipse IDEを用意し、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発するために、次の手順に固執します。
Step | Description |
---|---|
1 | Create a project with a name HelloWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes User, UserController under the com.finddevguidespackage. |
3 | Create view files user.jsp, users.jsp under the jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.finddevguides;
public class User {
private String username;
private String password;
private String address;
private boolean receivePaper;
private String [] favoriteFrameworks;
private String gender;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public boolean isReceivePaper() {
return receivePaper;
}
public void setReceivePaper(boolean receivePaper) {
this.receivePaper = receivePaper;
}
public String[] getFavoriteFrameworks() {
return favoriteFrameworks;
}
public void setFavoriteFrameworks(String[] favoriteFrameworks) {
this.favoriteFrameworks = favoriteFrameworks;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
UserController.java
package com.finddevguides;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user() {
User user = new User();
user.setFavoriteFrameworks((new String []{"Spring MVC","Struts 2"}));
user.setGender("M");
ModelAndView modelAndView = new ModelAndView("user", "command", user);
return modelAndView;
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
model.addAttribute("receivePaper", user.isReceivePaper());
model.addAttribute("favoriteFrameworks", user.getFavoriteFrameworks());
model.addAttribute("gender", user.getGender());
return "users";
}
@ModelAttribute("webFrameworkList")
public List<String> getWebFrameworkList()
{
List<String> webFrameworkList = new ArrayList<String>();
webFrameworkList.add("Spring MVC");
webFrameworkList.add("Struts 1");
webFrameworkList.add("Struts 2");
webFrameworkList.add("Apache Wicket");
return webFrameworkList;
}
}
ここでは、最初のサービスメソッド* user()で、ModelAndViewオブジェクトに「command」という名前の空白の *User オブジェクトを渡しました。これは、<form>を使用している場合、spring frameworkがJSPファイルの:form>タグ。 したがって、* user()メソッドが呼び出されると、 *user.jsp ビューが返されます。
2番目のサービスメソッド* addUser()は、 *HelloWeb/addUser URLのPOSTメソッドに対して呼び出されます。 送信された情報に基づいて、モデルオブジェクトを準備します。 最後に、「users」ビューがサービスメソッドから返され、users.jspがレンダリングされます。
user.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "/HelloWeb/addUser">
<table>
<tr>
<td><form:label path = "username">User Name</form:label></td>
<td><form:input path = "username"/></td>
</tr>
<tr>
<td><form:label path = "password">Age</form:label></td>
<td><form:password path = "password"/></td>
</tr>
<tr>
<td><form:label path = "address">Address</form:label></td>
<td><form:textarea path = "address" rows = "5" cols = "30"/></td>
</tr>
<tr>
<td><form:label path = "receivePaper">Subscribe Newsletter</form:label></td>
<td><form:checkbox path = "receivePaper"/></td>
</tr>
<tr>
<td><form:label path = "favoriteFrameworks">Favorite Web Frameworks</form:label></td>
<td><form:checkboxes items = "${webFrameworkList}" path = "favoriteFrameworks"/></td>
</tr>
<tr>
<td><form:label path = "gender">Gender</form:label></td>
<td>
<form:radiobutton path = "gender" value = "M" label = "Male"/>
<form:radiobutton path = "gender" value = "F" label = "Female"/>
</td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
ここでは、 <form:radiobutton/> タグを使用してHTMLラジオボタンをレンダリングしています。
<form:radiobutton path = "gender" value = "M" label = "Male"/>
<form:radiobutton path = "gender" value = "F" label = "Female"/>
次のHTMLコンテンツをレンダリングします。
<input id = "gender1" name = "gender" type = "radio" value = "M" checked = "checked"/><label for = "gender1">Male</label>
<input id = "gender2" name = "gender" type = "radio" value = "F"/><label for = "gender2">Female</label>
users.jsp
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
<tr>
<td>Address</td>
<td>${address}</td>
</tr>
<tr>
<td>Subscribed to Newsletter</td>
<td>${receivePaper}</td>
</tr>
<tr>
<td>Favorite Web Frameworks</td>
<td> <% String[] favoriteFrameworks = (String[])request.getAttribute("favoriteFrameworks");
for(String framework: favoriteFrameworks) {
out.println(framework);
}
%></td>
</tr>
<tr>
<td>Gender</td>
<td>${(gender=="M"? "Male" : "Female")}</td>
</tr>
</table>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 HelloWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLを試してください- http://localhost:8080/HelloWeb/user 。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
必要な情報を送信したら、送信ボタンをクリックしてフォームを送信します。 Spring Webアプリケーションで問題がなければ、次の画面が表示されます。
Spring MVC-RadioButtonsの例
次の例では、Spring Web MVCフレームワークを使用してフォームでRadioButtonsを使用する方法を説明します。 まず、動作するEclipse IDEを用意し、以降の手順に従って、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a project with a name HelloWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes User, UserController under the com.finddevguidespackage. |
3 | Create view files user.jsp, users.jsp under the jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.finddevguides;
public class User {
private String username;
private String password;
private String address;
private boolean receivePaper;
private String [] favoriteFrameworks;
private String gender;
private String favoriteNumber;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public boolean isReceivePaper() {
return receivePaper;
}
public void setReceivePaper(boolean receivePaper) {
this.receivePaper = receivePaper;
}
public String[] getFavoriteFrameworks() {
return favoriteFrameworks;
}
public void setFavoriteFrameworks(String[] favoriteFrameworks) {
this.favoriteFrameworks = favoriteFrameworks;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getFavoriteNumber() {
return favoriteNumber;
}
public void setFavoriteNumber(String favoriteNumber) {
this.favoriteNumber = favoriteNumber;
}
}
UserController.java
package com.finddevguides;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user() {
User user = new User();
user.setFavoriteFrameworks((new String []{"Spring MVC","Struts 2"}));
user.setGender("M");
ModelAndView modelAndView = new ModelAndView("user", "command", user);
return modelAndView;
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
model.addAttribute("receivePaper", user.isReceivePaper());
model.addAttribute("favoriteFrameworks", user.getFavoriteFrameworks());
model.addAttribute("gender", user.getGender());
model.addAttribute("favoriteNumber", user.getFavoriteNumber());
return "users";
}
@ModelAttribute("webFrameworkList")
public List<String> getWebFrameworkList() {
List<String> webFrameworkList = new ArrayList<String>();
webFrameworkList.add("Spring MVC");
webFrameworkList.add("Struts 1");
webFrameworkList.add("Struts 2");
webFrameworkList.add("Apache Wicket");
return webFrameworkList;
}
@ModelAttribute("numbersList")
public List<String> getNumbersList() {
List<String> numbersList = new ArrayList<String>();
numbersList.add("1");
numbersList.add("2");
numbersList.add("3");
numbersList.add("4");
return numbersList;
}
}
ここで、最初のサービスメソッドuser()に対して、ModelFormViewオブジェクトに「command」という名前の空のUserオブジェクトを渡しました。これは、<form:form>を使用している場合、Springフレームワークが「command」 JSPファイル内のタグ。 したがって、user()メソッドが呼び出されると、user.jspビューが返されます。
2番目のサービスメソッド* addUser()は、 *HelloWeb/addUser URLのPOSTメソッドに対して呼び出されます。 送信された情報に基づいて、モデルオブジェクトを準備します。 最後に、「users」ビューがサービスメソッドから返され、users.jspがレンダリングされます。
user.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "/HelloWeb/addUser">
<table>
<tr>
<td><form:label path = "username">User Name</form:label></td>
<td><form:input path = "username"/></td>
</tr>
<tr>
<td><form:label path = "password">Age</form:label></td>
<td><form:password path = "password"/></td>
</tr>
<tr>
<td><form:label path = "address">Address</form:label></td>
<td><form:textarea path = "address" rows = "5" cols = "30"/></td>
</tr>
<tr>
<td><form:label path = "receivePaper">Subscribe Newsletter</form:label></td>
<td><form:checkbox path = "receivePaper"/></td>
</tr>
<tr>
<td><form:label path = "favoriteFrameworks">Favorite Web Frameworks</form:label></td>
<td><form:checkboxes items = "${webFrameworkList}" path = "favoriteFrameworks"/></td>
</tr>
<tr>
<td><form:label path = "gender">Gender</form:label></td>
<td>
<form:radiobutton path = "gender" value = "M" label = "Male"/>
<form:radiobutton path = "gender" value = "F" label = "Female"/>
</td>
</tr>
<tr>
<td><form:label path = "favoriteNumber">Favorite Number</form:label></td>
<td>
<form:radiobuttons path = "favoriteNumber" items = "${numbersList}"/>
</td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
ここでは、* <form:radiobuttons/> *タグを使用してHTMLラジオボタンをレンダリングしています。 たとえば-
<form:radiobuttons path = "favoriteNumber" items="${numbersList}"/>
次のHTMLコンテンツをレンダリングします。
<span>
<input id = "favoriteNumber1" name = "favoriteNumber" type = "radio" value = "1"/>
<label for = "favoriteNumber1">1</label>
</span>
<span>
<input id = "favoriteNumber2" name = "favoriteNumber" type = "radio" value = "2"/>
<label for = "favoriteNumber2">2</label>
</span>
<span>
<input id = "favoriteNumber3" name = "favoriteNumber" type = "radio" value = "3"/>
<label for = "favoriteNumber3">3</label>
</span>
<span>
<input id = "favoriteNumber4" name = "favoriteNumber" type = "radio" value = "4"/>
<label for = "favoriteNumber4">4</label>
</span>
users.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
<tr>
<td>Address</td>
<td>${address}</td>
</tr>
<tr>
<td>Subscribed to Newsletter</td>
<td>${receivePaper}</td>
</tr>
<tr>
<td>Favorite Web Frameworks</td>
<td> <% String[] favoriteFrameworks = (String[])request.getAttribute("favoriteFrameworks");
for(String framework: favoriteFrameworks) {
out.println(framework);
}
%></td>
</tr>
<tr>
<td>Gender</td>
<td>${(gender=="M"? "Male" : "Female")}</td>
</tr>
<tr>
<td>Favourite Number</td>
<td>${favoriteNumber}</td>
</tr>
</table>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、*エクスポート→WARファイル*オプションを使用して、HelloWeb.warファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 次のURLを試してください– http://localhost:8080/HelloWeb/user 。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
必要な情報を送信したら、送信ボタンをクリックしてフォームを送信します。 Spring Webアプリケーションに問題がなければ、次の画面が表示されます。
Spring MVC-ドロップダウンの例
次の例では、Spring Web MVCフレームワークを使用してフォームでドロップダウンを使用する方法を説明します。 まず、動作するEclipse IDEを用意し、次の手順に従って、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a project with a name HelloWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes User, UserController under the com.finddevguidespackage. |
3 | Create view files user.jsp, users.jsp under the jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.finddevguides;
public class User {
private String username;
private String password;
private String address;
private boolean receivePaper;
private String [] favoriteFrameworks;
private String gender;
private String favoriteNumber;
private String country;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public boolean isReceivePaper() {
return receivePaper;
}
public void setReceivePaper(boolean receivePaper) {
this.receivePaper = receivePaper;
}
public String[] getFavoriteFrameworks() {
return favoriteFrameworks;
}
public void setFavoriteFrameworks(String[] favoriteFrameworks) {
this.favoriteFrameworks = favoriteFrameworks;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getFavoriteNumber() {
return favoriteNumber;
}
public void setFavoriteNumber(String favoriteNumber) {
this.favoriteNumber = favoriteNumber;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
UserController.java
package com.finddevguides;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user() {
User user = new User();
user.setFavoriteFrameworks((new String []{"Spring MVC","Struts 2"}));
user.setGender("M");
ModelAndView modelAndView = new ModelAndView("user", "command", user);
return modelAndView;
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
model.addAttribute("receivePaper", user.isReceivePaper());
model.addAttribute("favoriteFrameworks", user.getFavoriteFrameworks());
model.addAttribute("gender", user.getGender());
model.addAttribute("favoriteNumber", user.getFavoriteNumber());
model.addAttribute("country", user.getCountry());
return "users";
}
@ModelAttribute("webFrameworkList")
public List<String> getWebFrameworkList() {
List<String> webFrameworkList = new ArrayList<String>();
webFrameworkList.add("Spring MVC");
webFrameworkList.add("Struts 1");
webFrameworkList.add("Struts 2");
webFrameworkList.add("Apache Wicket");
return webFrameworkList;
}
@ModelAttribute("numbersList")
public List<String> getNumbersList() {
List<String> numbersList = new ArrayList<String>();
numbersList.add("1");
numbersList.add("2");
numbersList.add("3");
numbersList.add("4");
return numbersList;
}
@ModelAttribute("countryList")
public Map<String, String> getCountryList() {
Map<String, String> countryList = new HashMap<String, String>();
countryList.put("US", "United States");
countryList.put("CH", "China");
countryList.put("SG", "Singapore");
countryList.put("MY", "Malaysia");
return countryList;
}
}
ここでは、最初のサービスメソッド* user()に対して、ModelAndViewオブジェクトに「command」という名前の空の *User オブジェクトを渡しました。これは、Springフレームワークが、<command JSPファイルのform:form>タグ。 したがって、* user()メソッドが呼び出されると、 *user.jsp ビューが返されます。
2番目のサービスメソッド* addUser()は、 *HelloWeb/addUser URLのPOSTメソッドに対して呼び出されます。 送信された情報に基づいて、モデルオブジェクトを準備します。 最後に、「users」ビューがサービスメソッドから返され、users.jspがレンダリングされます。
user.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "/HelloWeb/addUser">
<table>
<tr>
<td><form:label path = "username">User Name</form:label></td>
<td><form:input path = "username"/></td>
</tr>
<tr>
<td><form:label path = "password">Age</form:label></td>
<td><form:password path = "password"/></td>
</tr>
<tr>
<td><form:label path = "address">Address</form:label></td>
<td><form:textarea path = "address" rows = "5" cols = "30"/></td>
</tr>
<tr>
<td><form:label path = "receivePaper">Subscribe Newsletter</form:label></td>
<td><form:checkbox path = "receivePaper"/></td>
</tr>
<tr>
<td><form:label path = "favoriteFrameworks">Favorite Web Frameworks</form:label></td>
<td><form:checkboxes items = "${webFrameworkList}" path = "favoriteFrameworks"/></td>
</tr>
<tr>
<td><form:label path = "gender">Gender</form:label></td>
<td>
<form:radiobutton path = "gender" value = "M" label = "Male"/>
<form:radiobutton path = "gender" value = "F" label = "Female"/>
</td>
</tr>
<tr>
<td><form:label path = "favoriteNumber">Favorite Number</form:label></td>
<td>
<form:radiobuttons path = "favoriteNumber" items = "${numbersList}"/>
</td>
</tr>
<tr>
<td><form:label path = "country">Country</form:label></td>
<td>
<form:select path = "country">
<form:option value = "NONE" label = "Select"/>
<form:options items = "${countryList}"/>
</form:select>
</td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
ここでは、 <form:select/>、<form:option/> および <form:options/> タグを使用して、HTMLのselectをレンダリングしています。 たとえば-
<form:select path = "country">
<form:option value = "NONE" label = "Select"/>
<form:options items = "${countryList}"/>
</form:select>
次のHTMLコンテンツをレンダリングします。
<select id = "country" name = "country">
<option value = "NONE">Select</option>
<option value = "US">United States</option>
<option value = "CH">China</option>
<option value = "MY">Malaysia</option>
<option value = "SG">Singapore</option>
</select>
users.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
<tr>
<td>Address</td>
<td>${address}</td>
</tr>
<tr>
<td>Subscribed to Newsletter</td>
<td>${receivePaper}</td>
</tr>
<tr>
<td>Favorite Web Frameworks</td>
<td> <% String[] favoriteFrameworks = (String[])request.getAttribute("favoriteFrameworks");
for(String framework: favoriteFrameworks) {
out.println(framework);
}
%></td>
</tr>
<tr>
<td>Gender</td>
<td>${(gender=="M"? "Male" : "Female")}</td>
</tr>
<tr>
<td>Favourite Number</td>
<td>${favoriteNumber}</td>
</tr>
<tr>
<td>Country</td>
<td>${country}</td>
</tr>
</table>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、HelloWeb.warファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLを試してください- http://localhost:8080/HelloWeb/user 。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
必要な情報を送信したら、送信ボタンをクリックしてフォームを送信します。 Spring Webアプリケーションで問題がなければ、次の画面が表示されます。
Spring MVC-リストボックスの例
次の例は、Spring Web MVCフレームワークを使用してフォームでリストボックスを使用する方法を示しています。 まず、動作するEclipse IDEを用意し、以降の手順に従って、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a project with a name HelloWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes User, UserController under the com.finddevguidespackage. |
3 | Create view files user.jsp, users.jsp under the jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.finddevguides;
public class User {
private String username;
private String password;
private String address;
private boolean receivePaper;
private String [] favoriteFrameworks;
private String gender;
private String favoriteNumber;
private String country;
private String [] skills;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public boolean isReceivePaper() {
return receivePaper;
}
public void setReceivePaper(boolean receivePaper) {
this.receivePaper = receivePaper;
}
public String[] getFavoriteFrameworks() {
return favoriteFrameworks;
}
public void setFavoriteFrameworks(String[] favoriteFrameworks) {
this.favoriteFrameworks = favoriteFrameworks;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getFavoriteNumber() {
return favoriteNumber;
}
public void setFavoriteNumber(String favoriteNumber) {
this.favoriteNumber = favoriteNumber;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String[] getSkills() {
return skills;
}
public void setSkills(String[] skills) {
this.skills = skills;
}
}
UserController.java
package com.finddevguides;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user() {
User user = new User();
user.setFavoriteFrameworks((new String []{"Spring MVC","Struts 2"}));
user.setGender("M");
ModelAndView modelAndView = new ModelAndView("user", "command", user);
return modelAndView;
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
model.addAttribute("receivePaper", user.isReceivePaper());
model.addAttribute("favoriteFrameworks", user.getFavoriteFrameworks());
model.addAttribute("gender", user.getGender());
model.addAttribute("favoriteNumber", user.getFavoriteNumber());
model.addAttribute("country", user.getCountry());
model.addAttribute("skills", user.getSkills());
return "users";
}
@ModelAttribute("webFrameworkList")
public List<String> getWebFrameworkList() {
List<String> webFrameworkList = new ArrayList<String>();
webFrameworkList.add("Spring MVC");
webFrameworkList.add("Struts 1");
webFrameworkList.add("Struts 2");
webFrameworkList.add("Apache Wicket");
return webFrameworkList;
}
@ModelAttribute("numbersList")
public List<String> getNumbersList() {
List<String> numbersList = new ArrayList<String>();
numbersList.add("1");
numbersList.add("2");
numbersList.add("3");
numbersList.add("4");
return numbersList;
}
@ModelAttribute("countryList")
public Map<String, String> getCountryList() {
Map<String, String> countryList = new HashMap<String, String>();
countryList.put("US", "United States");
countryList.put("CH", "China");
countryList.put("SG", "Singapore");
countryList.put("MY", "Malaysia");
return countryList;
}
@ModelAttribute("skillsList")
public Map<String, String> getSkillsList() {
Map<String, String> skillList = new HashMap<String, String>();
skillList.put("Hibernate", "Hibernate");
skillList.put("Spring", "Spring");
skillList.put("Apache Wicket", "Apache Wicket");
skillList.put("Struts", "Struts");
return skillList;
}
}
ここでは、最初のサービスメソッド* user()に対して、ModelAndViewオブジェクトに「command」という名前の空の *User オブジェクトを渡しました。これは、Springフレームワークが、<command JSPファイルのform:form>タグ。 したがって、* user()メソッドが呼び出されると、 *user.jsp ビューが返されます。
2番目のサービスメソッド* addUser()は、 *HelloWeb/addUser URLのPOSTメソッドに対して呼び出されます。 送信された情報に基づいて、モデルオブジェクトを準備します。 最後に、「users」ビューがサービスメソッドから返され、users.jspがレンダリングされます。
user.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "/HelloWeb/addUser">
<table>
<tr>
<td><form:label path = "username">User Name</form:label></td>
<td><form:input path = "username"/></td>
</tr>
<tr>
<td><form:label path = "password">Age</form:label></td>
<td><form:password path = "password"/></td>
</tr>
<tr>
<td><form:label path = "address">Address</form:label></td>
<td><form:textarea path = "address" rows = "5" cols = "30"/></td>
</tr>
<tr>
<td><form:label path = "receivePaper">Subscribe Newsletter</form:label></td>
<td><form:checkbox path = "receivePaper"/></td>
</tr>
<tr>
<td><form:label path = "favoriteFrameworks">Favorite Web Frameworks</form:label></td>
<td><form:checkboxes items = "${webFrameworkList}" path = "favoriteFrameworks"/></td>
</tr>
<tr>
<td><form:label path = "gender">Gender</form:label></td>
<td>
<form:radiobutton path = "gender" value = "M" label = "Male"/>
<form:radiobutton path = "gender" value = "F" label = "Female"/>
</td>
</tr>
<tr>
<td><form:label path = "favoriteNumber">Favorite Number</form:label></td>
<td>
<form:radiobuttons path = "favoriteNumber" items = "${numbersList}"/>
</td>
</tr>
<tr>
<td><form:label path = "country">Country</form:label></td>
<td>
<form:select path = "country">
<form:option value = "NONE" label = "Select"/>
<form:options items = "${countryList}"/>
</form:select>
</td>
</tr>
<tr>
<td><form:label path = "skills">Skills</form:label></td>
<td>
<form:select path = "skills" items = "${skillsList}"
multiple = "true"/>
</td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
ここでは、属性 multiple = true を持つ <form:select/> タグを使用して、HTMLリストボックスをレンダリングしています。 たとえば-
<form:select path = "skills" items = "${skillsList}" multiple = "true"/>
次のHTMLコンテンツをレンダリングします。
<select id = "skills" name = "skills" multiple = "multiple">
<option value = "Struts">Struts</option>
<option value = "Hibernate">Hibernate</option>
<option value = "Apache Wicket">Apache Wicket</option>
<option value = "Spring">Spring</option>
</select>
<input type = "hidden" name = "_skills" value = "1"/>
users.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
<tr>
<td>Address</td>
<td>${address}</td>
</tr>
<tr>
<td>Subscribed to Newsletter</td>
<td>${receivePaper}</td>
</tr>
<tr>
<td>Favorite Web Frameworks</td>
<td> <% String[] favoriteFrameworks = (String[])request.getAttribute("favoriteFrameworks");
for(String framework: favoriteFrameworks) {
out.println(framework);
}
%></td>
</tr>
<tr>
<td>Gender</td>
<td>${(gender=="M"? "Male" : "Female")}</td>
</tr>
<tr>
<td>Favourite Number</td>
<td>${favoriteNumber}</td>
</tr>
<tr>
<td>Country</td>
<td>${country}</td>
</tr>
<tr>
<td>Skills</td>
<td> <% String[] skills = (String[])request.getAttribute("skills");
for(String skill: skills) {
out.println(skill);
}
%></td>
</tr>
</table>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、*エクスポート→WARファイル*オプションを使用して、HelloWeb.warファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLを試してください- http://localhost:8080/HelloWeb/user 。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
必要な情報を送信したら、送信ボタンをクリックしてフォームを送信します。 Spring Webアプリケーションで問題がなければ、次の画面が表示されます。
スプリングリストボックスフォームの結果 Springmvc-hidden
Spring MVC-エラー処理の例
次の例は、Spring Web MVCフレームワークを使用してフォームでエラー処理とバリデーターを使用する方法を示しています。 まず、動作するEclipse IDEを用意し、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発するための次の手順を検討します。
Step | Description |
---|---|
1 | Create a project with a name HelloWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes Student, StudentController and StudentValidator under the com.finddevguides package. |
3 | Create view files addStudent.jsp, result.jsp under the jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
Student.java
package com.finddevguides;
public class Student {
private Integer age;
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
StudentValidator.java
package com.finddevguides;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
public class StudentValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return Student.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors,
"name", "required.name","Field name is required.");
}
}
StudentController.java
package com.finddevguides;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class StudentController {
@Autowired
@Qualifier("studentValidator")
private Validator validator;
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setValidator(validator);
}
@RequestMapping(value = "/addStudent", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("addStudent", "command", new Student());
}
@ModelAttribute("student")
public Student createStudentModel() {
return new Student();
}
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("student") @Validated Student student,
BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
return "addStudent";
}
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
HelloWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.finddevguides"/>
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean id = "studentValidator" class = "com.finddevguides.StudentValidator"/>
</beans>
ここで、最初のサービスメソッド* student()に対して、ModelAndViewオブジェクトに空のStudentobjectを "command"という名前で渡しました。これは、<form:formを使用している場合、Springフレームワークが "command" > JSPファイルのタグ。 したがって、student()メソッドが呼び出されると、 *addStudent.jsp ビューが返されます。
2番目のサービスメソッド* addStudent()は、 *HelloWeb/addStudent URLのPOSTメソッドに対して呼び出されます。 送信された情報に基づいて、モデルオブジェクトを準備します。 最後に、サービスメソッドから「結果」ビューが返され、result.jspがレンダリングされます。 バリデーターを使用してエラーが生成された場合、同じビュー「addStudent」が返され、Springはビューの BindingResult からエラーメッセージを自動的に挿入します。
addStudent.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<style>
.error {
color: #ff0000;
}
.errorblock {
color: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
<body>
<h2>Student Information</h2>
<form:form method = "POST" action = "/HelloWeb/addStudent" commandName = "student">
<form:errors path = "*" cssClass = "errorblock" element = "div"/>
<table>
<tr>
<td><form:label path = "name">Name</form:label></td>
<td><form:input path = "name"/></td>
<td><form:errors path = "name" cssClass = "error"/></td>
</tr>
<tr>
<td><form:label path = "age">Age</form:label></td>
<td><form:input path = "age"/></td>
</tr>
<tr>
<td><form:label path = "id">id</form:label></td>
<td><form:input path = "id"/></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
ここでは、エラーメッセージを表示するためにpath = ""で *<form:errors/> タグを使用しています。 例えば
<form:errors path = "*" cssClass = "errorblock" element = "div"/>
すべての入力検証のエラーメッセージを表示します。
*<form:errors/>* タグをpath = "name"で使用して、名前フィールドのエラーメッセージを表示しています。 例えば
<form:errors path = "name" cssClass = "error"/>
名前フィールド検証のエラーメッセージを表示します。
result.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 HelloWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLを試してください- http://localhost:8080/HelloWeb/addStudent 。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
必要な情報を送信したら、送信ボタンをクリックしてフォームを送信します。 Spring Webアプリケーションで問題がなければ、次の画面が表示されます。
Spring MVC-ファイルのアップロードの例
次の例は、Spring Web MVCフレームワークを使用してフォームでファイルアップロードコントロールを使用する方法を示しています。 まず、動作するEclipse IDEを用意し、次の手順に従って、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a project with a name HelloWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes FileModel, FileUploadController under the com.finddevguides package. |
3 | Create view files fileUpload.jsp, success.jsp under the jsp sub-folder. |
4 | Create a folder temp under the WebContent sub-folder. |
5 | Download Apache Commons FileUpload library commons-fileupload.jar and Apache Commons IO library commons-io.jar. Put them in your CLASSPATH. |
6 | The final step is to create the content of the source and configuration files and export the application as explained below. |
FileModel.java
package com.finddevguides;
import org.springframework.web.multipart.MultipartFile;
public class FileModel {
private MultipartFile file;
public MultipartFile getFile() {
return file;
}
public void setFile(MultipartFile file) {
this.file = file;
}
}
FileUploadController.java
package com.finddevguides;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class FileUploadController {
@Autowired
ServletContext context;
@RequestMapping(value = "/fileUploadPage", method = RequestMethod.GET)
public ModelAndView fileUploadPage() {
FileModel file = new FileModel();
ModelAndView modelAndView = new ModelAndView("fileUpload", "command", file);
return modelAndView;
}
@RequestMapping(value="/fileUploadPage", method = RequestMethod.POST)
public String fileUpload(@Validated FileModel file, BindingResult result, ModelMap model) throws IOException {
if (result.hasErrors()) {
System.out.println("validation errors");
return "fileUploadPage";
} else {
System.out.println("Fetching file");
MultipartFile multipartFile = file.getFile();
String uploadPath = context.getRealPath("") + File.separator + "temp" + File.separator;
//Now do something with file...
FileCopyUtils.copy(file.getFile().getBytes(), new File(uploadPath+file.getFile().getOriginalFilename()));
String fileName = multipartFile.getOriginalFilename();
model.addAttribute("fileName", fileName);
return "success";
}
}
}
HelloWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.finddevguides"/>
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean id = "multipartResolver"
class = "org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
</beans>
ここでは、最初のサービスメソッド* fileUploadPage()に対して、ModelAndViewオブジェクトの空の *FileModel オブジェクトを "command"という名前で渡しました。これは、< JSPファイルのform:form>タグ。 したがって、* fileUploadPage()メソッドが呼び出されると、 *fileUpload.jsp ビューが返されます。
2番目のサービスメソッド* fileUpload()は、 *HelloWeb/fileUploadPage URLのPOSTメソッドに対して呼び出されます。 送信された情報に基づいて、アップロードするファイルを準備します。 最後に、サービスメソッドから「成功」ビューが返され、success.jspがレンダリングされます。
fileUpload.jsp
<%@ page contentType="text/html; charset = UTF-8" %>
<%@ taglib prefix = "form" uri = "http://www.springframework.org/tags/form"%>
<html>
<head>
<title>File Upload Example</title>
</head>
<body>
<form:form method = "POST" modelAttribute = "fileUpload"
enctype = "multipart/form-data">
Please select a file to upload :
<input type = "file" name = "file"/>
<input type = "submit" value = "upload"/>
</form:form>
</body>
</html>
ここでは、value = "fileUpload"を指定した modelAttribute 属性を使用して、ファイルアップロードコントロールをサーバーモデルにマップしています。
success.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>File Upload Example</title>
</head>
<body>
FileName :
lt;b> ${fileName} </b> - Uploaded Successfully.
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、*エクスポート→WARファイル*オプションを使用して、HelloWeb.warファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLを試してください– http://localhost:8080/HelloWeb/fileUploadPage 。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
必要な情報を送信したら、送信ボタンをクリックしてフォームを送信します。 Spring Webアプリケーションで問題がなければ、次の画面が表示されます。
Spring MVC-Bean名URLハンドラーマッピングの例
次の例は、Spring Web MVCフレームワークを使用してBean名URLハンドラーマッピングを使用する方法を示しています。 BeanNameUrlHandlerMapping クラスはデフォルトのハンドラーマッピングクラスであり、URLリクエストを構成に記載されているBeanの名前にマップします。
<beans>
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name = "/helloWorld"
class = "com.finddevguides.HelloController"/>
<bean name = "/hello*"
class = "com.finddevguides.HelloController"/>
<bean name = "/welcome"
class = "com.finddevguides.WelcomeController"/>
</beans>
たとえば、URIの場合、上記の構成を使用します
/helloWorldまたは/hello \ {any letter}がリクエストされると、DispatcherServletはリクエストを *HelloController に転送します。 /welcomeが要求されると、DispatcherServletはその要求を *WelcomeController に転送します。 */welcome1が要求された場合、DispatcherServletはコントローラーを検出せず、サーバーは404ステータスエラーをスローします。
まず、動作するEclipse IDEを用意し、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発するための次の手順を検討します。
Step | Description |
---|---|
1 | Create a project with a name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes HelloController, WelcomeController under the com.finddevguides package. |
3 | Create view files hello.jsp, welcome.jsp under the jsp sub-folder. |
4 | The final step is to create the content of all source and configuration files and export the application as explained below. |
HelloController.java
package com.finddevguides;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class HelloController extends AbstractController{
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("hello");
model.addObject("message", "Hello World!");
return model;
}
}
WelcomeController.java
package com.finddevguides;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class WelcomeController extends AbstractController{
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("welcome");
model.addObject("message", "Welcome!");
return model;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name = "/helloWorld"
class = "com.finddevguides.HelloController"/>
<bean name = "/hello*"
class = "com.finddevguides.HelloController"/>
<bean name = "/welcome"
class = "com.finddevguides.WelcomeController"/>
</beans>
hello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
welcome.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 TestWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLを試してください- http://localhost:8080/TestWeb/helloWorld 。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
URLを試してください- http://localhost:8080/TestWeb/hello 。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
*http://localhost:8080/TestWeb/welcome* というURLを試してみてください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
*http://localhost:8080/TestWeb/welcome1* というURLを試してみてください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
Spring MVC-コントローラークラス名ハンドラーマッピングの例
次の例は、Spring Web MVCフレームワークを使用してコントローラークラス名ハンドラーマッピングを使用する方法を示しています。 ControllerClassNameHandlerMapping クラスは、規則ベースのハンドラーマッピングクラスです。このクラスは、URLリクエストを構成で指定されているコントローラーの名前にマップします。 このクラスは、コントローラー名を取得し、先頭に「/」を付けて小文字に変換します。
たとえば、HelloControllerは「/hello *」URLにマップします。
<beans>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean class = "com.finddevguides.HelloController"/>
<bean class = "com.finddevguides.WelcomeController"/>
</beans>
たとえば、上記の構成を使用して、URI
/helloWorldまたは/hello \ {any letter}がリクエストされると、DispatcherServletはリクエストを *HelloController に転送します。 /welcomeが要求されると、DispatcherServletはその要求を *WelcomeController に転送します。 */Welcomeは、Wが大文字の場合に要求され、DispatcherServletはコントローラーを検出せず、サーバーは404ステータスエラーをスローします。
まず、作業中のEclipse IDEを用意し、以降の手順に従ってSpring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a project with a name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes HelloController and WelcomeController under the com.finddevguides package. |
3 | Create view files hello.jsp, welcome.jsp under the jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
HelloController.java
package com.finddevguides;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class HelloController extends AbstractController{
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("hello");
model.addObject("message", "Hello World!");
return model;
}
}
WelcomeController.java
package com.finddevguides;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class WelcomeController extends AbstractController{
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("welcome");
model.addObject("message", "Welcome!");
return model;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean class = "com.finddevguides.HelloController"/>
<bean class = "com.finddevguides.WelcomeController"/>
</beans>
hello.jsp
<%@ page contentType="text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
welcome.jsp
<%@ page contentType = "text/html; charset=UTF-8" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 TestWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLを試してください- http://localhost:8080/TestWeb/helloWorld 。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
Spring Controller Class Name Handler Mapping 1
*http://localhost:8080/TestWeb/hello* というURLを試してみてください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
Spring Controller Class Name Handler Mapping 2
*http://localhost:8080/TestWeb/welcome* というURLを試してみてください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
Spring Controller Class Name Handler Mapping 3
*http://localhost:8080/TestWeb/Welcome* というURLを試してみてください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
Spring Controller Class Name Handler Mapping 4
Spring MVC-シンプルなURLハンドラーマッピングの例
次の例は、Spring Web MVCフレームワークを使用して単純なURLハンドラーマッピングを使用する方法を示しています。 SimpleUrlHandlerMappingクラスは、それぞれのコントローラーにURLを明示的にマッピングするのに役立ちます。
<beans>
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name = "mappings">
<props>
<prop key = "/welcome">welcomeController</prop>
<prop key = "/helloWorld">helloController</prop>
</props>
</property>
</bean>
<bean id = "helloController" class = "com.finddevguides.HelloController"/>
<bean id = "welcomeController" class = "com.finddevguides.WelcomeController"/>
</beans>
たとえば、上記の構成を使用して、URI
/helloWorldが要求されると、DispatcherServletはその要求を *HelloController に転送します。 /welcomeが要求されると、DispatcherServletはその要求を *WelcomeController に転送します。
まず、動作するEclipse IDEを用意し、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発するための次の手順を検討します。
Step | Description |
---|---|
1 | Create a project with a name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes HelloController and WelcomeController under the com.finddevguides package. |
3 | Create view files hello.jsp and welcome.jsp under the jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
HelloController.java
package com.finddevguides;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class HelloController extends AbstractController{
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("hello");
model.addObject("message", "Hello World!");
return model;
}
}
WelcomeController.java
package com.finddevguides;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class WelcomeController extends AbstractController{
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("welcome");
model.addObject("message", "Welcome!");
return model;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name = "mappings">
<props>
<prop key = "/welcome">welcomeController</prop>
<prop key = "/helloWorld">helloController</prop>
</props>
</property>
</bean>
<bean id = "helloController" class = "com.finddevguides.HelloController"/>
<bean id = "welcomeController" class = "com.finddevguides.WelcomeController"/>
</beans>
hello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
welcome.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、Tomcatのwebappsフォルダーに TestWeb.war ファイルを保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLを試してください- http://localhost:8080/TestWeb/helloWorld 。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
Spring Controller Class Name Handler Mapping 1
*http://localhost:8080/TestWeb/welcome* というURLを試してみてください。SpringWebアプリケーションで問題がなければ、次の結果が表示されるはずです。
Spring Controller Class Name Handler Mapping 2
Spring MVC-マルチアクションコントローラーの例
次の例は、Spring Web MVCフレームワークを使用してマルチアクションコントローラーを使用する方法を示しています。 MultiActionController クラスは、単一のコントローラー内のメソッドを使用して複数のURLをそれぞれマップするのに役立ちます。
package com.finddevguides;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController{
public ModelAndView home(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("home");
model.addObject("message", "Home");
return model;
}
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Add");
return model;
}
public ModelAndView remove(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Remove");
return model;
}
}
<bean class = "org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name = "/home" class = "com.finddevguides.UserController"/>
<bean name = "/user/*" class = "com.finddevguides.UserController"/>
たとえば、URIの場合、上記の構成を使用して-
*/homeが要求されると、DispatcherServletは要求をUserController* home()*メソッドに転送します。
*user/addが要求されると、DispatcherServletはその要求をUserController* add()*メソッドに転送します。
*user/removeがリクエストされると、DispatcherServletはリクエストをUserController* remove()*メソッドに転送します。
はじめに、作業中のEclipse IDEを用意し、次の手順に従って、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a project with a name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create a Java class UserController under the com.finddevguides package. |
3 | Create view files home.jsp and user.jsp under the jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
UserController.java
package com.finddevguides;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController{
public ModelAndView home(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("home");
model.addObject("message", "Home");
return model;
}
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Add");
return model;
}
public ModelAndView remove(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Remove");
return model;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name = "/home"
class = "com.finddevguides.UserController"/>
<bean name = "/user/*"
class = "com.finddevguides.UserController"/>
</beans>
home.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = ISO-8859-1">
<title>Home</title>
</head>
<body>
<a href = "user/add" >Add</a> <br>
<a href = "user/remove" >Remove</a>
</body>
</html>
user.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 TestWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 ここで、URL- http://localhost:8080/TestWeb/home を試してください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
Spring Multi Action Controller 1
*http://localhost:8080/TestWeb/user/add* というURLを試してください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
Spring Multi Action Controller 2
Spring MVC-プロパティメソッド名リゾルバーの例
次の例は、Spring Web MVCフレームワークを使用して、Multi Action ControllerのProperties Method Name Resolverメソッドを使用する方法を示しています。 MultiActionController クラスは、単一のコントローラー内のメソッドを使用して複数のURLをそれぞれマップするのに役立ちます。
package com.finddevguides;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController{
public ModelAndView home(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Home");
return model;
}
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Add");
return model;
}
public ModelAndView remove(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Remove");
return model;
}
}
<bean class = "com.finddevguides.UserController">
<property name = "methodNameResolver">
<bean class = "org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
<property name = "mappings">
<props>
<prop key = "/user/home">home</prop>
<prop key = "/user/add">add</prop>
<prop key = "/user/remove">update</prop>
</props>
</property>
</bean>
</property>
</bean>
たとえば、URIの場合、上記の構成を使用して-
*/user/homeが要求されると、DispatcherServletは要求をUserController* home()*メソッドに転送します。
*/user/addが要求されると、DispatcherServletは要求をUserController* add()*メソッドに転送します。
*/user/removeが要求されると、DispatcherServletは要求をUserController* remove()*メソッドに転送します。
最初に、動作するEclipse IDEを用意し、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発するための次の手順を検討します。
Step | Description |
---|---|
1 | Create a project with a name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java class UserController under the com.finddevguides package. |
3 | Create a view file user.jsp under the jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
UserController.java
package com.finddevguides;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController{
public ModelAndView home(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Home");
return model;
}
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Add");
return model;
}
public ModelAndView remove(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Remove");
return model;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<property name = "caseSensitive" value = "true"/>
</bean>
<bean class = "com.finddevguides.UserController">
<property name = "methodNameResolver">
<bean class = "org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
<property name = "mappings">
<props>
<prop key = "/user/home">home</prop>
<prop key = "/user/add">add</prop>
<prop key = "/user/remove">update</prop>
</props>
</property>
</bean>
</property>
</bean>
</beans>
user.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 TestWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 ここで、URL- http://localhost:8080/TestWeb/user/add を試してください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
Spring Multi Action Controller
Spring MVC-パラメーターメソッド名リゾルバーの例
次の例は、Spring Web MVCフレームワークを使用して、Multi Action ControllerのParameter Method Name Resolverを使用する方法を示しています。 MultiActionController クラスは、単一のコントローラー内のメソッドを使用して複数のURLをそれぞれマップするのに役立ちます。
package com.finddevguides;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController{
public ModelAndView home(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Home");
return model;
}
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Add");
return model;
}
public ModelAndView remove(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Remove");
return model;
}
}
<bean class = "com.finddevguides.UserController">
<property name = "methodNameResolver">
<bean class = "org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name = "paramName" value = "action"/>
</bean>
</property>
</bean>
たとえば、URIの場合、上記の構成を使用して-
*/user/* ?action = homeが要求されると、DispatcherServletはその要求をUserController * home()*メソッドに転送します。
*/user/* ?action = addが要求されると、DispatcherServletはその要求をUserController * add()*メソッドに転送します。
*/user/* ?action = removeが要求されると、DispatcherServletはその要求をUserController * remove()*メソッドに転送します。
まず、動作するEclipse IDEを用意し、次の手順に従って、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a project with a name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create a Java class UserController under the com.finddevguides package. |
3 | Create a view file user.jsp under the jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
UserController.java
package com.finddevguides;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController{
public ModelAndView home(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Home");
return model;
}
public ModelAndView add(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Add");
return model;
}
public ModelAndView remove(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Remove");
return model;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
<property name = "caseSensitive" value = "true"/>
</bean>
<bean class = "com.finddevguides.UserController">
<property name = "methodNameResolver">
<bean class = "org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
<property name = "paramName" value = "action"/>
</bean>
</property>
</bean>
</beans>
user.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 TestWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 ここで、URL- http://localhost:8080/TestWeb/user/test?action = home を試してください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
Spring Multi Action Controller
Spring MVC-パラメーター化可能なView Controllerの例
次の例は、Spring Web MVCフレームワークを使用してマルチアクションコントローラーのParameterizable View Controllerメソッドを使用する方法を示しています。 パラメータ化可能なビューでは、Webページをリクエストにマッピングできます。
package com.finddevguides;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController{
public ModelAndView home(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Home");
return model;
}
}
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<value>
index=userController
</value>
</property>
</bean>
<bean id="userController" class="org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name="viewName" value="user"/>
</bean>
たとえば、URIの場合、上記の構成を使用します。
/indexがリクエストされると、DispatcherServletはリクエストを *UserController コントローラに転送し、viewNameをuser.jspに設定します。
それを開始するために、作業中のEclipse IDEを用意し、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発するために、次の手順に固執します。
Step | Description |
---|---|
1 | Create a project with a name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create a Java class UserController under the com.finddevguides package. |
3 | Create a view file user.jsp under the jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
UserController.java
package com.finddevguides;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
public class UserController extends MultiActionController{
public ModelAndView home(HttpServletRequest request,
HttpServletResponse response) throws Exception {
ModelAndView model = new ModelAndView("user");
model.addObject("message", "Home");
return model;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
<bean class = "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name = "mappings">
<value>
index = userController
</value>
</property>
</bean>
<bean id = "userController" class = "org.springframework.web.servlet.mvc.ParameterizableViewController">
<property name = "viewName" value="user"/>
</bean>
</beans>
user.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>Hello World</h2>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 TestWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 ここで、URL – http://localhost:8080/TestWeb/index を試してください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
Spring Multi Action Controller
Spring MVC-内部リソースビューリゾルバーの例
*InternalResourceViewResolver* は、提供されたURIを実際のURIに解決するために使用されます。 次の例は、Spring Web MVCフレームワークを使用してInternalResourceViewResolverを使用する方法を示しています。 InternalResourceViewResolverを使用すると、Webページをリクエストにマッピングできます。
package com.finddevguides;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
たとえば、URIの場合、上記の構成を使用します
- /helloが要求されると、DispatcherServletは要求をプレフィックス+ビュー名+サフィックス=/WEB-INF/jsp/hello.jspに転送します。
まず、動作するEclipse IDEを用意し、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発するための次の手順を検討します。
Step | Description |
---|---|
1 | Create a project with a name TestWeb under a package com.finddevguidesas explained in the Spring MVC - Hello World Example chapter. |
2 | Create a Java classes HelloController under the com.finddevguidespackage. |
3 | Create a view file hello.jsp under jsp sub-folder. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
HelloController.java
package com.finddevguides;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.finddevguides"/>
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
</beans>
hello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 TestWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URL- http://localhost:8080/TestWeb/hello にアクセスしてみてください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
Spring Internal Resource View Resolver
Spring MVC-XMLビューリゾルバーの例
XmlViewResolverは、xmlファイルで定義されたビューBeanを使用してビュー名を解決するために使用されます。 次の例は、Spring Web MVCフレームワークを使用してXmlViewResolverを使用する方法を示しています。
TestWeb-servlet.xml
<bean class = "org.springframework.web.servlet.view.XmlViewResolver">
<property name = "location">
<value>/WEB-INF/views.xml</value>
</property>
</bean>
views.xml
<bean id = "hello"
class = "org.springframework.web.servlet.view.JstlView">
<property name = "url" value = "/WEB-INF/jsp/hello.jsp"/>
</bean>
たとえば、URIの場合、上記の構成を使用して-
- /helloが要求されると、DispatcherServletは要求をview.xmlのbean helloで定義されたhello.jspに転送します。
まず、動作するEclipse IDEを用意し、次の手順に従って、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a project with a name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create a Java class HelloController under the com.finddevguidespackage. |
3 | Create a view file hello.jsp under the jsp sub-folder. |
4 | Download JSTL library jstl.jar. Put it in your CLASSPATH. |
5 | The final step is to create the content of the source and configuration files and export the application as explained below. |
HelloController.java
package com.finddevguides;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.finddevguides"/>
<bean class = "org.springframework.web.servlet.view.XmlViewResolver">
<property name = "location">
<value>/WEB-INF/views.xml</value>
</property>
</bean>
</beans>
views.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id = "hello"
class = "org.springframework.web.servlet.view.JstlView">
<property name = "url" value = "/WEB-INF/jsp/hello.jsp"/>
</bean>
</beans>
hello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 HelloWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URL- http://localhost:8080/HelloWeb/hello にアクセスしてみてください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
Spring Internal Resource View Resolver
Spring MVC-リソースバンドルビューリゾルバーの例
*ResourceBundleViewResolver* は、プロパティファイルで定義されたビューBeanを使用してビュー名を解決するために使用されます。 次の例は、Spring Web MVCフレームワークを使用してResourceBundleViewResolverを使用する方法を示しています。
TestWeb-servlet.xml
<bean class = "org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name = "basename" value = "views"/>
</bean>
ここで、 basename は、ビューを運ぶリソースバンドルの名前を指します。 リソースバンドルのデフォルト名は views.properties で、basenameプロパティを使用してオーバーライドできます。
views.properties
hello.(class) = org.springframework.web.servlet.view.JstlView
hello.url =/WEB-INF/jsp/hello.jsp
たとえば、URIの場合、上記の構成を使用して-
/helloが要求された場合、DispatcherServletは要求をviews.propertiesのbean helloで定義されたhello.jspに転送します。 * ここで、「hello」は一致するビュー名です。 一方、 *class はビュータイプを指し、URLはビューの場所です。
まず、動作するEclipse IDEを用意し、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発するための次の手順を検討します。
Step | Description |
---|---|
1 | Create a project with a name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create a Java class HelloController under the com.finddevguidespackage. |
3 | Create a view file hello.jsp under the jsp sub-folder. |
4 | Create a properties file views.properties under the src folder. |
5 | Download JSTL library jstl.jar. Put it in your CLASSPATH. |
6 | The final step is to create the content of the source and configuration files and export the application as explained below. |
HelloController.java
package com.finddevguides;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.finddevguides"/>
<bean class = "org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name = "basename" value = "views"/>
</bean>
</beans>
views.properties
hello.(class) = org.springframework.web.servlet.view.JstlView
hello.url =/WEB-INF/jsp/hello.jsp
hello.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、HelloWeb.warファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URL- http://localhost:8080/HelloWeb/hello にアクセスしてみてください。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
Spring Internal Resource View Resolver
Spring MVC-複数のリゾルバーマッピングの例
Spring MVCアプリケーションでMultiple View Resolverを使用する場合、orderプロパティを使用して優先順位を設定できます。 次の例は、Spring Web MVCフレームワークで ResourceBundleViewResolver および InternalResourceViewResolver を使用する方法を示しています。
TestWeb-servlet.xml
<bean class = "org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name = "basename" value = "views"/>
<property name = "order" value = "0"/>
</bean>
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
<property name = "order" value = "1"/>
</bean>
ここで、orderプロパティは、ビューリゾルバーのランキングを定義します。 この場合、0は最初のリゾルバであり、1は次のリゾルバなどです。
views.properties
hello.(class) = org.springframework.web.servlet.view.JstlView
hello.url =/WEB-INF/jsp/hello.jsp
たとえば、URIの場合、上記の構成を使用して-
- /helloが要求されると、DispatcherServletは、要求をviews.propertiesのbean helloで定義されたhello.jspに転送します。
まず、動作するEclipse IDEを用意し、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発するための次の手順を検討します。
Step | Description |
---|---|
1 | Create a project with a name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create a Java class HelloController under the com.finddevguidespackage. |
3 | Create a view file hello.jsp under the jsp sub-folder. |
4 | Create a properties file views.properties under the SRC folder. |
5 | Download the JSTL library jstl.jar. Put it in your CLASSPATH. |
6 | The final step is to create the content of the source and configuration files and export the application as explained below. |
HelloController.java
package com.finddevguides;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "hello";
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.finddevguides"/>
<bean class = "org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name = "basename" value = "views"/>
<property name = "order" value = "0"/>
</bean>
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
<property name = "order" value = "1"/>
</bean>
</beans>
views.properties
hello.(class) = org.springframework.web.servlet.view.JstlView
hello.url =/WEB-INF/jsp/hello.jsp
hello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、エクスポート→WARファイル*オプションを使用して、 *HelloWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLにアクセスしてみてください- http://localhost:8080/HelloWeb/hello 。SpringWebアプリケーションで問題がなければ、次の画面が表示されます。
Spring Internal Resource View Resolver
Spring MVC-Hibernate Validatorの例
次の例は、Spring Web MVCフレームワークを使用してフォームでエラー処理とバリデーターを使用する方法を示しています。 まず、動作するEclipse IDEを用意し、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発するための次の手順を順守します。
Step | Description |
---|---|
1 | Create a project with the name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes Student, StudentController and StudentValidator under the com.finddevguides package. |
3 | Create view files addStudent.jsp and result.jsp under the jsp sub-folder. |
4 | Download Hibernate Validator library Hibernate Validator. Extract hibernate-validator-5.3.4.Final.jar and required dependencies present under the required folder of the downloaded zip file. Put them in your CLASSPATH. |
5 | Create a properties file messages.properties under the SRC folder. |
6 | The final step is to create the content of the source and configuration files and export the application as explained below. |
Student.java
package com.finddevguides;
import org.hibernate.validator.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
public class Student {
@Range(min = 1, max = 150)
private Integer age;
@NotEmpty
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
StudentController.java
package com.finddevguides;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class StudentController {
@RequestMapping(value = "/addStudent", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("addStudent", "command", new Student());
}
@ModelAttribute("student")
public Student createStudentModel() {
return new Student();
}
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("student") @Validated Student student,
BindingResult bindingResult, Model model) {
if (bindingResult.hasErrors()) {
return "addStudent";
}
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
}
messages.properties
NotEmpty.student.name = Name is required!
Range.student.age = Age value must be between 1 and 150!
ここで、キーは<Annotation>。<object-name>。<attribute>です。 値は表示されるメッセージです。
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:mvc = "http://www.springframework.org/schema/mvc"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package = "com.finddevguides"/>
<mvc:annotation-driven/>
<bean class = "org.springframework.context.support.ResourceBundleMessageSource"
id = "messageSource">
<property name = "basename" value = "messages"/>
</bean>
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
</beans>
ここでは、最初のサービスメソッド* student()について、ModelAndViewオブジェクトに「command」という名前の空白の *Studentobject> を渡しました。これは、Springフレームワークが、<command JSPファイルのform:form>タグ。 したがって、* student()メソッドが呼び出されると、 *addStudent.jsp ビューが返されます。
2番目のサービスメソッド* addStudent()は、 *HelloWeb/addStudent URLのPOSTメソッドに対して呼び出されます。 送信された情報に基づいて、モデルオブジェクトを準備します。 最後に、サービスメソッドから「結果」ビューが返され、result.jspがレンダリングされます。 バリデーターを使用してエラーが生成された場合、同じビュー「addStudent」が返され、Springはビューの BindingResult からエラーメッセージを自動的に挿入します。
addStudent.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<style>
.error {
color: #ff0000;
}
.errorblock {
color: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
<body>
<h2>Student Information</h2>
<form:form method = "POST" action = "/TestWeb/addStudent" commandName = "student">
<form:errors path = "*" cssClass = "errorblock" element = "div"/>
<table>
<tr>
<td><form:label path = "name">Name</form:label></td>
<td><form:input path = "name"/></td>
<td><form:errors path = "name" cssClass = "error"/></td>
</tr>
<tr>
<td><form:label path = "age">Age</form:label></td>
<td><form:input path = "age"/></td>
<td><form:errors path = "age" cssClass = "error"/></td>
</tr>
<tr>
<td><form:label path = "id">id</form:label></td>
<td><form:input path = "id"/></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
ここでは、path = "*"で<form:errors/>タグを使用してエラーメッセージをレンダリングしています。 たとえば-
<form:errors path = "*" cssClass = "errorblock" element = "div"/>
すべての入力検証のエラーメッセージを表示します。 <form:errors/>タグでpath = "name"を使用して、名前フィールドのエラーメッセージを表示しています。
たとえば-
<form:errors path = "name" cssClass = "error"/>
<form:errors path = "age" cssClass = "error"/>
名前と年齢フィールドの検証のエラーメッセージを表示します。
result.jsp
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
<tr>
<td>ID</td>
<td>${id}</td>
</tr>
</table>
</body>
</html>
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 HelloWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLを試してください- http://localhost:8080/TestWeb/addStudent 。無効な値を入力した場合、次の画面が表示されます。
Spring MVC-RSSフィードの生成の例
次の例は、Spring Web MVCフレームワークを使用してRSSフィードを生成する方法を示しています。 まず、動作するEclipse IDEを用意し、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発するための次の手順を検討します。
Step | Description |
---|---|
1 | Create a project with the name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes RSSMessage, RSSFeedViewer and RSSController under the com.finddevguides package. |
3 | Download the Rome library Rome and its dependencies rome-utils, jdom and slf4j from the same maven repository page. Put them in your CLASSPATH. |
4 | Create a properties file messages.properties under the SRC folder. |
5 | The final step is to create the content of the source and configuration files and export the application as explained below. |
RSSMessage.java
package com.finddevguides;
import java.util.Date;
public class RSSMessage {
String title;
String url;
String summary;
Date createdDate;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
}
RSSFeedViewer.java
package com.finddevguides;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.feed.AbstractRssFeedView;
import com.rometools.rome.feed.rss.Channel;
import com.rometools.rome.feed.rss.Content;
import com.rometools.rome.feed.rss.Item;
public class RSSFeedViewer extends AbstractRssFeedView {
@Override
protected void buildFeedMetadata(Map<String, Object> model, Channel feed,
HttpServletRequest request) {
feed.setTitle("finddevguides Dot Com");
feed.setDescription("Java Tutorials and Examples");
feed.setLink("http://www.finddevguides.com");
super.buildFeedMetadata(model, feed, request);
}
@Override
protected List<Item> buildFeedItems(Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response) throws Exception {
List<RSSMessage> listContent = (List<RSSMessage>) model.get("feedContent");
List<Item> items = new ArrayList<Item>(listContent.size());
for(RSSMessage tempContent : listContent ){
Item item = new Item();
Content content = new Content();
content.setValue(tempContent.getSummary());
item.setContent(content);
item.setTitle(tempContent.getTitle());
item.setLink(tempContent.getUrl());
item.setPubDate(tempContent.getCreatedDate());
items.add(item);
}
return items;
}
}
RSSController.java
package com.finddevguides;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class RSSController {
@RequestMapping(value="/rssfeed", method = RequestMethod.GET)
public ModelAndView getFeedInRss() {
List<RSSMessage> items = new ArrayList<RSSMessage>();
RSSMessage content = new RSSMessage();
content.setTitle("Spring Tutorial");
content.setUrl("http://www.finddevguides/spring");
content.setSummary("Spring tutorial summary...");
content.setCreatedDate(new Date());
items.add(content);
RSSMessage content2 = new RSSMessage();
content2.setTitle("Spring MVC");
content2.setUrl("http://www.finddevguides/springmvc");
content2.setSummary("Spring MVC tutorial summary...");
content2.setCreatedDate(new Date());
items.add(content2);
ModelAndView mav = new ModelAndView();
mav.setViewName("rssViewer");
mav.addObject("feedContent", items);
return mav;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.finddevguides"/>
<bean class = "org.springframework.web.servlet.view.BeanNameViewResolver"/>
<bean id = "rssViewer" class = "com.finddevguides.RSSFeedViewer"/>
</beans>
ここでは、 AbstractRssFeedView を拡張し、そのメソッドをオーバーライドするRSSフィードPOJO RSSMessageとRSSメッセージビューアーを作成しました。 RSSControllerで、サンプルRSSフィードを生成しました。
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 TestWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLを試してください- http://localhost:8080/TestWeb/rssfeed すると、次の画面が表示されます。
Spring MVC-XMLの生成の例
次の例は、Spring Web MVCフレームワークを使用してXMLを生成する方法を示しています。 はじめに、作業中のEclipse IDEを用意し、次の手順に従って、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a project with a name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes User and UserController under the com.finddevguidespackage. |
3 | The final step is to create the content of the source and configuration files and export the application as explained below. |
User.java
package com.finddevguides;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "user")
public class User {
private String name;
private int id;
public String getName() {
return name;
}
@XmlElement
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
@XmlElement
public void setId(int id) {
this.id = id;
}
}
UserController.java
package com.finddevguides;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value="{name}", method = RequestMethod.GET)
public @ResponseBody User getUser(@PathVariable String name) {
User user = new User();
user.setName(name);
user.setId(1);
return user;
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc = "http://www.springframework.org/schema/mvc"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package = "com.finddevguides"/>
<mvc:annotation-driven/>
</beans>
ここでは、XMLマップされたPOJOユーザーを作成し、UserControllerでユーザーを返しました。 Springは RequestMapping に基づいてXML変換を自動的に処理します。
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 TestWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLを試してください– http://localhost:8080/TestWeb/mahesh 。次の画面が表示されます。
Spring MVC-JSONの生成の例
次の例は、Spring Web MVCフレームワークを使用してJSONを生成する方法を示しています。 まず、動作するEclipse IDEを用意し、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発するための次の手順を検討します。
Step | Description |
---|---|
1 | Create a project with a name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create a Java classes User, UserController under the com.finddevguides package. |
3 | Download Jackson libraries Jackson Core, Jackson Databind and Jackson Annotations from maven repository page. Put them in your CLASSPATH. |
4 | The final step is to create the content of all the source and configuration files and export the application as explained below. |
User.java
package com.finddevguides;
public class User {
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
UserController.java
package com.finddevguides;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value="{name}", method = RequestMethod.GET)
public @ResponseBody User getUser(@PathVariable String name) {
User user = new User();
user.setName(name);
user.setId(1);
return user;
}
}
TestWeb-servlet.xml
<beans xmlns = http://www.springframework.org/schema/beans"
xmlns:context = http://www.springframework.org/schema/context"
xmlns:xsi = http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc = http://www.springframework.org/schema/mvc"
xsi:schemaLocation =
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package = com.finddevguides"/>
<mvc:annotation-driven/>
</beans>
ここでは、単純なPOJOユーザーを作成し、UserControllerでユーザーを返しました。 Springは、クラスパスに存在するRequestMappingとJackson jarに基づいてJSON変換を自動的に処理します。
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 TestWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLを試してください– http://localhost:8080/TestWeb/mahesh 。次の画面が表示されます。
Spring MVC-Excelの生成の例
次の例は、Spring Web MVCフレームワークを使用してExcelを生成する方法を示しています。 はじめに、作業中のEclipse IDEを用意し、次の手順に従って、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a project with a name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes UserExcelView and ExcelController under the com.finddevguides package. |
3 | Download the Apache POI library Apache POI from the maven repository page. Put it in your CLASSPATH. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
ExcelController.java
package com.finddevguides;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class ExcelController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
//user data
Map<String,String> userData = new HashMap<String,String>();
userData.put("1", "Mahesh");
userData.put("2", "Suresh");
userData.put("3", "Ramesh");
userData.put("4", "Naresh");
return new ModelAndView("UserSummary","userData",userData);
}
}
UserExcelView.java
package com.finddevguides;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.view.document.AbstractExcelView;
public class UserExcelView extends AbstractExcelView {
@Override
protected void buildExcelDocument(Map<String, Object> model,
HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Map<String,String> userData = (Map<String,String>) model.get("userData");
//create a wordsheet
HSSFSheet sheet = workbook.createSheet("User Report");
HSSFRow header = sheet.createRow(0);
header.createCell(0).setCellValue("Roll No");
header.createCell(1).setCellValue("Name");
int rowNum = 1;
for (Map.Entry<String, String> entry : userData.entrySet()) {
//create the row data
HSSFRow row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(entry.getKey());
row.createCell(1).setCellValue(entry.getValue());
}
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc = "http://www.springframework.org/schema/mvc"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean class = "org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean class = "com.finddevguides.ExcelController"/>
<bean class = "org.springframework.web.servlet.view.XmlViewResolver">
<property name = "location">
<value>/WEB-INF/views.xml</value>
</property>
</bean>
</beans>
views.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id = "UserSummary" class = "com.finddevguides.UserExcelView"></bean>
</beans>
ここで、ExcelControllerとExcelViewを作成しました。 Apache POIライブラリはMicrosoft Officeファイル形式を扱い、データをExcelドキュメントに変換します。
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 TestWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLを試してください- http://localhost:8080/TestWeb/excel 。次の画面が表示されます。
Spring MVC-PDFの生成の例
次の例は、Spring Web MVCフレームワークを使用してPDFを生成する方法を示しています。 まず、動作するEclipse IDEを用意し、次の手順に従って、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a project with a name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create Java classes UserPDFView and PDFController under the com.finddevguides package. |
3 | Download the iText library − iText from the maven repository page. Put it in your CLASSPATH. |
4 | The final step is to create the content of the source and configuration files and export the application as explained below. |
PDFController.java
package com.finddevguides;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class PDFController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
//user data
Map<String,String> userData = new HashMap<String,String>();
userData.put("1", "Mahesh");
userData.put("2", "Suresh");
userData.put("3", "Ramesh");
userData.put("4", "Naresh");
return new ModelAndView("UserSummary","userData",userData);
}
}
UserExcelView.java
package com.finddevguides;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.view.document.AbstractPdfView;
import com.lowagie.text.Document;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.PdfWriter;
public class UserPDFView extends AbstractPdfView {
protected void buildPdfDocument(Map<String, Object> model, Document document,
PdfWriter pdfWriter, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Map<String,String> userData = (Map<String,String>) model.get("userData");
Table table = new Table(2);
table.addCell("Roll No");
table.addCell("Name");
for (Map.Entry<String, String> entry : userData.entrySet()) {
table.addCell(entry.getKey());
table.addCell(entry.getValue());
}
document.add(table);
}
}
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc = "http://www.springframework.org/schema/mvc"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<bean class = "org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
<bean class = "com.finddevguides.PDFController"/>
<bean class = "org.springframework.web.servlet.view.XmlViewResolver">
<property name = "location">
<value>/WEB-INF/views.xml</value>
</property>
</bean>
</beans>
views.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id = "UserSummary" class = "com.finddevguides.UserPDFView"></bean>
</beans>
ここでは、PDFControllerとUserPDFViewを作成しました。 iTextライブラリはPDFファイル形式を処理し、データをPDFドキュメントに変換します。
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 TestWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 また、次のURLを試すこともできます- http://localhost:8080/TestWeb/pdf 。すべてが計画どおりに進んだ場合、次の画面が表示されます。
Spring MVC-LOG4Jの統合の例
次の例は、Spring Web MVC Frameworkを使用してLOG4Jを統合する方法を示しています。 まず、動作するEclipse IDEを用意し、次の手順に従って、Spring Web Frameworkを使用して動的フォームベースのWebアプリケーションを開発します。
Step | Description |
---|---|
1 | Create a project with the name TestWeb under a package com.finddevguides as explained in the Spring MVC - Hello World chapter. |
2 | Create a Java class HelloController under the com.finddevguidespackage. |
3 | Download the log4j library LOG4J from the maven repository page. Put it in your CLASSPATH. |
4 | Create a log4j.properties under the SRC folder. |
5 | The final step is to create the content of the source and configuration files and export the application as explained below. |
HelloController.java
package com.finddevguides;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.ModelMap;
@Controller
@RequestMapping("/hello")
public class HelloController{
private static final Logger LOGGER = Logger.getLogger(HelloController.class);
@RequestMapping(method = RequestMethod.GET)
public String printHello(ModelMap model) {
LOGGER.info("printHello started.");
//logs debug message
if(LOGGER.isDebugEnabled()){
LOGGER.debug("Inside: printHello");
}
//logs exception
LOGGER.error("Logging a sample exception", new Exception("Testing"));
model.addAttribute("message", "Hello Spring MVC Framework!");
LOGGER.info("printHello ended.");
return "hello";
}
}
log4j.properties
# Root logger option
log4j.rootLogger = DEBUG, stdout, file
# Redirect log messages to console
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Redirect log messages to a log file
log4j.appender.file = org.apache.log4j.RollingFileAppender
#outputs to Tomcat home
log4j.appender.file.File = ${catalina.home}/logs/myapp.log
log4j.appender.file.MaxFileSize = 5MB
log4j.appender.file.MaxBackupIndex = 10
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
TestWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc = "http://www.springframework.org/schema/mvc"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package = "com.finddevguides"/>
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"/>
<property name = "suffix" value = ".jsp"/>
</bean>
</beans>
hello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
ここでは、Tomcatコンソールおよび&t;にあるファイルに詳細を記録するようにLOG4Jを構成しました。 tomcat home→myapp.logとしてログに記録します。
ソースファイルと構成ファイルの作成が完了したら、アプリケーションをエクスポートします。 アプリケーションを右クリックし、[エクスポート]→[WARファイル]オプションを使用して、 TestWeb.war ファイルをTomcatのwebappsフォルダーに保存します。
次に、Tomcatサーバーを起動し、標準ブラウザーを使用してwebappsフォルダーから他のWebページにアクセスできることを確認します。 URLを試してください-* http://localhost:8080/TestWeb/hello *。Tomcatのログに次の画面が表示されます。