Spring Boot+FullCalendar+JSONで実験してみた


Spring Bootでカレンダー表示をやってみたい、と思い実験してみました。

使ったライブラリとバージョン

サンプルプロジェクトの中身

EclipseでSpring Starter Projectを作成し、こんな感じのプロジェクトにしました。

設定追加

pom.xml

以下を追加。

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>2.0.3</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.bower</groupId>
            <artifactId>moment</artifactId>
            <version>2.19.1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars.bower</groupId>
            <artifactId>fullcalendar</artifactId>
            <version>3.5.1</version>
        </dependency>

モデル作成

FullCalendarのサンプルやドキュメントを参考に、簡単なモデルクラスを作成しました。

event.java
package com.example.model;

/**
 * FullCalendar用Event Object
 * 
 * @see https://fullcalendar.io/docs/event_data/Event_Object/
 */
public class Event {

    private String title;

    /**
     * カレンダーの開始日付
     */
    private String start;

    /**
     * カレンダーの終了日付
     */
    private String end;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getStart() {
        return start;
    }
    public void setStart(String start) {
        this.start = start;
    }
    public String getEnd() {
        return end;
    }
    public void setEnd(String end) {
        this.end = end;
    }
}

コントローラー作成

筆者がSpring Bootを使い始めて間もなく理解不足のため、ちょっと回りくどい実装になっているかもしれません・・・

CalendarController.java
package com.example.controller;

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


@Controller
public class CalendarController {

    @RequestMapping(path = "/calendar", method = RequestMethod.GET)
    String index(Model model) {
        return "calendar/index";
    }
}
RestWebController.java
package com.example.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.model.Event;
import com.fasterxml.jackson.databind.ObjectMapper;


@RestController
@RequestMapping("/api/event")
public class RestWebController {

    /**
     * カレンダーに表示するEvent情報を取得
     * @return Event情報をjsonエンコードした文字列
     */
    @GetMapping(value = "/all")
    public String getEvents() {
        String jsonMsg = null;
        try {
            List<Event> events = new ArrayList<Event>();
            Event event = new Event();
            event.setTitle("first event");
            event.setStart("2017-10-01");
            events.add(event);

            event = new Event();
            event.setTitle("second event");
            event.setStart("2017-10-11");
            event.setEnd("2017-10-12");
            events.add(event);

            // FullCalendarにエンコード済み文字列を渡す
            ObjectMapper mapper = new ObjectMapper();
            jsonMsg =  mapper.writerWithDefaultPrettyPrinter().writeValueAsString(events);
        } catch (IOException ioex) {
            System.out.println(ioex.getMessage());
        }
        return jsonMsg;
    }
}
CalendarDemoApplication.java
package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CalendarDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(CalendarDemoApplication.class, args);
    }
}


画面作成

カレンダーをデフォルト設定で表示させます。

index.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>calendar demo</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel='stylesheet' href='webjars/fullcalendar/3.5.1/dist/fullcalendar.css' />
<script src="webjars/jquery/2.0.3/jquery.min.js"></script>
<script src='webjars/moment/2.19.1/min/moment.min.js'></script>
<script src='webjars/fullcalendar/3.5.1/dist/fullcalendar.js'></script>
<script type="text/javascript">
  $(document).ready(function() {
    $('#calendar').fullCalendar({
      events: {
        url : '/api/event/all'
      }
    });
  });
</script>
</head>
<body>
  <div id='calendar'></div>
</body>
</html>

動作確認

Spring Boot Appよりcalendar-demoを起動し、http://127.0.0.1:8080 を開いてください。
カレンダーに2件のイベントが表示されていればOKです。

参考サイト

How to integrate JQuery Ajax POST/GET & Spring MVC | Spring Boot
Convert Java Object to JSON and Vice Versa