LoginSignup
6
5

More than 5 years have passed since last update.

Spring4を使ってみる(・8・)

Posted at

Springおじさんにならなくては

お仕事でSpringを使っていく風潮が出てきたので、設定とかアノテーションとかをさらっておこうと思います。一先ず、RESTapiを一個作ってGETしてみる

依存関係

この記事書いた時点で最新の'spring-webmvc'をペタリ。'spring-web'ていうのもあったけれど、viewを返すMVCフレームワークを使ってみたかったのでとりあえずこれで

build.gradle
compile group: 'org.springframework', name: 'spring-webmvc', version: '4.3.1.RELEASE'
compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.0'

ひとくちにSpringと言っても色々あるみたい。他のはまたそのうち。

jsonで返却して欲しいので、jackson先生もぺたり

設定ファイル1

まずはサーブレットの設定ということで、web.xml

web.xml

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

    <servlet>
        <servlet-name>servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>servlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.hoge.ServletContext</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>
  • servletタグ
  • servlet-mappingタグ
  • context-paramタグ
    • Springの設定を色々書く"servlet-context.xml”をJavaで書くことも出来るらしい。
    • そのクラスをparamに渡してあげる。
    • XMLで書くなら、そのファイルをのパスを渡す
  • listenerタグ
    • HTTPリクエストを受け取ってSpringプロセスへごにょごにょしてくれるクラスを登録する
    • "DispatcherServlet"以外にもいくつかあるっぽい?

設定ファイルクラス2

web.xmlでparamに渡したConfigクラス

ServletContext.java
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.hoge")
public class ServletContext {}
  • @Configuration
    • 設定ファイル、というかクラスの宣言
  • @EnableWebMvc
    • SpringMVCの有効化
  • @ComponentScan(basePackages = "com.hoge")
    • エンドポイントを定義するControllerクラスを検索するパッケージを指定する

Controllerクラス

UserRestController.java
@RestController
@RequestMapping("/api/users")
public class UserRestController {

    @RequestMapping(
            value = "/",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public List<User> getUsers(){

        User user1 = new User("name1");
        User user2 = new User("name2");
        List<User> users = new ArrayList();
        users.add(user1);
        users.add(user2);

        return users;
    }

    public class User{
        public String name;
        User (String name){
            this.name = name;
        }
    }
}
  • @RestController
    • WebAPIとして文字列やらを返却するメソッドを定義するクラスにアノテートする
    • ちなみに、@Controllerはviewを返却するクラスにアノテートする
  • @RequestMapping
    • value
      • エンドポイントのパス
      • パスを変数にして引数に渡すことが出来る
      • {"path1", "path2"}の形で2パターン以上のパスを定義できるみたいだけれど、何に使うのか分からない
    • method
      • HTTPメソッドを定義する。
      • せっかく定数定義されているのでそっちを使う。
    • produces
      • 返却するメディア・タイプを指定する。
      • application/jsonみたいに文字列を入れればいいけれど、せっかく定数定、、、略

war作ってtomcatにおいて、、、、、、、

スクリーンショット 2016-07-13 0.57.26.png

ヤッター(・8・)

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5