Spring 3では、古いRequestMappingクラスがRESTfulな機能をサポートするように拡張されているため、Spring開発者はSpring MVCでRESTサービスを簡単に開発できます。

このチュートリアルでは、

Spring 3 MVCアノテーション

を使用してRESTfulスタイルのWebアプリケーションを開発する方法を説明します。

1.プロジェクトディレクトリ

プロジェクトのフォルダ構造を確認します。


image、title = "spring-mvc-rest-hello-world"、width = 451、height = 394

プロジェクトの依存関係

Spring MVCでRESTを開発するには、SpringのSpringとSpringのMVCの中核となる依存関係を追加してください。

pom.xml

    <properties>
        <spring.version>3.0.5.RELEASE</spring.version>
    </properties>

    <dependencies>

        <!-- Spring 3 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

    </dependencies>

</project>

3. RESTコントローラ

Spring RESTfulの場合は、

PathVariable

、` RequestMapping`、 `RequestMethod`が必要です。以下のコードは、自明のものでなければなりません。

MovieController.java

package com.mkyong.common.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/movie")
public class MovieController {

    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
    public String getMovie(@PathVariable String name, ModelMap model) {

        model.addAttribute("movie", name);
        return "list";

    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String getDefaultMovie(ModelMap model) {

        model.addAttribute("movie", "this is default movie");
        return "list";

    }

}

4. JSPビュー

値を表示するJSPページ。

list.jsp

<html>
<body>
    <h1>Spring 3 MVC REST web service</h1>

    <h2>Movie Name : ${movie}</h2>
</body>
</html>

5.デモ

REST URLのデモンストレーションを参照してください。


Spring MVC RESTのデモ、タイトル= "spring-mvc-rest-demo1"、width = 552、height = 284


spring mvc rest demo、title = "spring-mvc-rest-demo2"、width = 552、height = 284

ソースコードをダウンロードする

ダウンロードする –

Spring3MVC-REST-HelloWorld-Example.zip

(7 KB)