Spring MVC の例

「Spring MVCの例へようこそ。以前にSpring MVCチュートリアルで、Spring Tool Suiteを使用してSpring MVCアプリケーションを作成する方法を説明しました。しかし、今日はmavenとEclipseを使って基本的なハローワールドSpring MVCアプリケーションを作成します。」

Spring MVC の例題

Spring MVCはModel-View-Controllerアーキテクチャーに基づいています。以下の画像は、Spring MVCのアーキテクチャーを高いレベルで示しています。DispatcherServletはフロントコントローラークラスであり、すべてのリクエストを受け取り処理を開始します。web.xmlファイルで設定する必要があります。その役割は、リクエストを適切なコントローラークラスに渡し、ビューページがレスポンスページをレンダリングした後にレスポンスを送信することです。HomeController.javaは、Spring MVCのサンプルアプリケーションにおける単一のコントローラークラスです。home.jsp、user.jspは、Spring MVCのハローワールドサンプルアプリケーションにおけるビューページです。User.javaは、Spring MVCのサンプルWebアプリケーションにおける唯一のモデルクラスです。

Spring MVCの例 こんにちは、世界 Eclipseプロジェクト

以下の画像は、私たちのSpring MVCのEclipseでのサンプルプロジェクトを示しています。さあ、最初からプロジェクトを作成しましょう。

「Spring MVCの例」「Eclipseプロジェクトのセットアップ」

ウェブアプリケーションであり、依存関係の管理にはMavenを使用するため、まず、動的なウェブアプリケーションを作成し、それをMavenプロジェクトに変換する必要があります。以下の画像は、この作業を行い、プロジェクトの骨組みを準備する方法を示しています。プロジェクトエクスプローラーウィンドウで右クリックし、「新規→動的Webプロジェクト」とクリックします。次のポップアップページで「spring-mvc-example」という名前を指定し、その他の項目は変更する必要はありません。次のページで、ソースフォルダを「src/main/java」と指定します。これを追加する前に、リストから「src」フォルダを削除する必要があるかもしれません。次は、ウェブモジュールページで、アプリケーションのコンテキストルートを「spring-mvc-example」と指定し、「web.xmlデプロイ記述子を生成する」オプションをチェックしてください。完了をクリックすると、Eclipseのプロジェクトエクスプローラーに新しい動的Webプロジェクトが作成されます。

動的なウェブプロジェクトをメイブンプロジェクトに変換する

私たちは、Spring MVCの依存関係を簡単に管理するためにMavenを使用したいと考えています。ですので、ウェブプロジェクトをMavenに変換しましょう。プロジェクトを右クリックし、「Configure -> Convert to Maven Project」と選択してください。次に、以下に示すようにpom.xmlの設定を提供してください。Mavenウェブアプリケーションのプロジェクトスケルトンコードが準備できました。これで、変更を加えてSpring MVCのハローワールドの例アプリケーションを作成できます。

pom.xmlにSpring MVCの依存関係を追加してください。

pom.xmlには、spring-webおよびspring-webmvcの依存関係を追加する必要があります。さらに、servlet-api、jsp-api、およびjstlの依存関係も追加してください。最終的なpom.xmlファイルは以下のようになります。

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.scdev.spring.mvc</groupId>
	<artifactId>spring-mvc-example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<name>Spring MVC Example</name>
	<description>Spring MVC Hello World Example</description>

	<!-- Add Spring Web and MVC dependencies -->
	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.3.9.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.3.9.RELEASE</version>
		</dependency>
		<!-- Servlet -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.6.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.0.0</version>
				<configuration>
					<warSourceDirectory>WebContent</warSourceDirectory>
				</configuration>
			</plugin>
		</plugins>
		<finalName>${project.artifactId}</finalName> <!-- added to remove Version from WAR file -->
	</build>
</project>

ビルドのfinalName設定に注意してください。これにより、WARファイル名にバージョンの詳細が含まれなくなります。Eclipseでプロジェクトをビルドすると、全てのjarファイルがMavenの依存関係セクションに表示されることに気付くでしょう。

スプリングMVCのDispatcherServletはフロントコントローラーとして機能します。

私たちは、ウェブアプリケーションにSpring MVCフレームワークを追加しなければなりません。そのためには、以下に示すようにweb.xmlでDispatcherServletを設定する必要があります。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>spring-mvc-example</display-name>

	<!-- Add Spring MVC DispatcherServlet as front controller -->
	<servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
                org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
       		<param-name>contextConfigLocation</param-name>
       		<param-value>/WEB-INF/spring-servlet.xml</param-value>
    		</init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern> 
    </servlet-mapping>
    
 </web-app>

contextConfigLocation(init-param)は、Springビーンの設定ファイルの場所を指定するために使用されます。

春のMVCの例、Beanの設定ファイル

次のステップは、以下に示すようにspring-servlet.xmlというSpringビーン設定ファイルを作成することです。

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="https://www.springframework.org/schema/mvc"
	xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:beans="https://www.springframework.org/schema/beans"
	xmlns:context="https://www.springframework.org/schema/context"
	xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
		https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing 
		infrastructure -->

	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />
	<context:component-scan base-package="com.scdev.spring" />

	<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
		in the /WEB-INF/views directory -->
	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

</beans:beans>

重要な構成は3つあります。

    1. アノテーション駆動によって、DispatcherServletは@Controllerアノテーションを使用してControllerクラスを検索します。

 

    1. context:component-scanによって、DispatcherServletはControllerクラスを検索する場所を指定します。

 

    InternalResourceViewResolverのBean構成によって、ビューページの場所と使用する接尾辞が指定されます。Controllerクラスのメソッドはビューページの名前を返し、接尾辞が追加されてレスポンスのレンダリングに使用するビューページが決定されます。

スプリングMVCのコントローラークラス

ホームページのための “/” と、ユーザーページのための “/user” の2つのURIに対応するための単一のコントローラークラスがあります。

package com.scdev.spring.controller;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.scdev.spring.model.User;

@Controller
public class HomeController {

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		System.out.println("Home Page Requested, locale = " + locale);
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

		String formattedDate = dateFormat.format(date);

		model.addAttribute("serverTime", formattedDate);

		return "home";
	}

	@RequestMapping(value = "/user", method = RequestMethod.POST)
	public String user(@Validated User user, Model model) {
		System.out.println("User Page Requested");
		model.addAttribute("userName", user.getUserName());
		return "user";
	}
}

簡単のため、log4jなどのログフレームワークを使用していないことに注意してください。

スプリング MVCのモデルクラス

シンプルなモデルクラスを持っています。単一の変数とそのゲッター・セッターメソッドがあります。これはシンプルなPOJOクラスです。

package com.scdev.spring.model;

public class User {
	private String userName;

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}
}

Spring MVCのビューページ

以下で定義された2つのビューページを持っています。home.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="https://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page session="false"%>
<html>
<head>
<title>Home</title>
</head>
<body>
	<h1>Hello world!</h1>

	<P>The time on the server is ${serverTime}.</p>

	<form action="user" method="post">
		<input type="text" name="userName"><br> <input
			type="submit" value="Login">
	</form>
</body>
</html>

ユーザー.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Home Page</title>
</head>
<body>
<h3>Hi ${userName}</h3>
</body>
</html>

Spring MVCは、フォームの変数をモデルクラスの変数にマッピングすることを自動的に処理してくれることに気づいてください。そのため、両方の場所で同じ変数名を使用しています。これで、私たちのSpring MVCのサンプルプロジェクトはデプロイとテストの準備が完了しました。

Spring MVCのEclipseプロジェクトのデプロイ

EclipseのWARファイルエクスポートオプションを利用して、実行中のTomcatサーバーのwebappsディレクトリに直接デプロイすることができます。ただし、プロジェクトをビルドしてからコマンドラインでお好みのサーブレットコンテナのデプロイディレクトリにコピーすることもできます。

Spring MVCのテストの例

春のMVCプロジェクトがデプロイされると、https://localhost:8080/spring-mvc-example/でホームページにアクセスできます。Tomcatのポートとコンテキストルートを適切に変更してください。これで春のMVCの例は以上です。可能な限りシンプルにしようとしましたが、何か問題があればコメントで教えてください。助けになるように努めます。最終的なSpring MVCの例プロジェクトは以下のリンクからダウンロードできます。

「Spring MVCのサンプルプロジェクトをダウンロードする」

参考文献:公式サイト

コメントを残す 0

Your email address will not be published. Required fields are marked *