Spring WebMVCをやってみる (1)

2013-12-03T00:00:00+00:00 gradle Java Spring Framework

タイトル通り、まぁ特に依存性注入するとか細かい所は今回無しな方向で画面にテキストを出すだけな事をSpring WebMVCを使ってやってみる。まぁ要は使い方の一歩目的な感じで

build.gradle

apply plugin: "war"
apply plugin: "eclipse"
apply plugin: "jetty"

repositories {
    mavenCentral()
}

dependencies {
    compile "javax.servlet:servlet-api:2.5"
    compile "org.springframework:spring-webmvc:3.2.5.RELEASE"

    testCompile "junit:junit:4.11"
    testCompile "org.hamcrest:hamcrest-all:1.3"
    testCompile "org.springframework:spring-test:3.2.5.RELEASE"
}

ただ依存性を取ってくる的な所辺りだけ。

src/main/webapp/WEB-INF/web.xml

<?xml version="1.0" ?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
    <servlet>
        <servlet-name>spring-web</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-web-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-web</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

src/main/resources/spring-web-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:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    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="sample" />

</beans>

base-packageでコントローラー等でアノテーションを使って多様な処理をする際に、そのクラスのパッケージを指定出来る的な感じだと思われる。

SampleController.java

package sample;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/sample")
public class SampleController {

    @RequestMapping("/index")
    public void index(HttpServletResponse response)
        throws Exception {
        response.setStatus(200);
        response.getWriter().print("hoge fuga foobar");
    }

    @RequestMapping("/test")
    public void test(HttpServletResponse response)  throws Exception{
        response.setStatus(200);
        response.getWriter().print("test");
    }
}

的な感じでやって

gradle jettyRun

でJettyサーバーを起動後、http://localhost:8080/[context_root]/sample/index.action とかでアクセスするとURLに対応した@RequestMappingアノテーションで指定されたメソッドが作用する

っていう感じで作れると。んじゃテストしましょうかと

SampleControllerTest.java

package swmvc;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.web.context.WebApplicationContext;

import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-web-servlet.xml")
@WebAppConfiguration
public class SampleControllerTest {

    @Autowired
    private WebApplicationContext context;

    private MockMvc mvc;

    @Before
    public void setUp() {
        mvc = webAppContextSetup(context).build();
    }

    @Test
    public void test_run() throws Exception {
        mvc.perform(get("/sample/index"))
            .andExpect(status().isOk())
            .andExpect(content().string("hoge fuga foobar"));

        MvcResult result = mvc.perform(get("/sample/index")).andReturn();
        assertThat(result, notNullValue());

        MockHttpServletResponse response = result.getResponse();
        assertThat(response, notNullValue());
        assertThat(response.getStatus(), is(200));

        // fail
        assertThat(response.getContentAsString(), is("hoge"));
    }
}

んまぁMockHttpServletResponseを作って、コントローラークラスのメソッドに普通に指定しちゃえばテスト出来ると思われるので

とまぁSpring WebMVCのファーストステップとしてはこんな所で。もちろん勉強はこれからもちょこちょこやっていく予定

CasperJSを使ったJavaScriptのテスト DialogFragmentのsetShowsDialog