Creating a Web Event Calendar Using the Spring Framework

In this tutorial we’d like to show you how how to use the JavaPlanner library with the Spring framework. You will create a simple web application with the planner populated with data from a database and able to save changes back on the server.

This is the first of the tutorials trilogy describing using JavaPlanner with the Java frameworks:

The tutorial assumes that you have previous knowledge of the Spring framework and the JavaPlanner library. If you haven’t, please follow the links below to get the required information:

All files related to the tutorial can be downloaded here.

Step 1. New project

Create a new dynamic project and name it 'demoapp'.

Step 2. Required code files

After setting up a new project, add the required code files into build path. They are:

  • Spring framework jar files;
  • Hibernate jar files;
  • dhtmlxScheduler library files (it’s a client-side library that provides creating JavaPlanner on the page);
  • javaplanner.jar file (you can download it here).

You can find all the mentioned files in the supplied package.

Step 3. Spring servlet declaration and configuration

On this step we should declare the Dispatcher Servlet and configure it.
The Dispatcher Servlet dispatches client requests to controllers. It's declared in the web.xml file of your application and maps requests using URL mapping.

  • Alter the content of a web.xml file to configure the dispatcher;
  • Create a demoapp-servlet.xml file and define configurations required for handling user requests there.

As the aforementioned actions are a common practice, we won't describe them in depth.
To see the files definitions, check out web.xml and demoapp-servlet.xml in the supplied package (demoapp/WebContent/WEB-INF):

Step 4. Data to load

In the tutorials we will use data from the demoapp_spring.sql dump file (the file resides in the root folder of the supplied package). You can create a local copy of this database by importing an demoapp_spring.sql dump file or use any available database. But note, if you use a custom database you will need to adapt the code stated in the tutorial by yourself.

Step 5. The mapping file

In our app we will use the Hibernate library to store and retrieve data from the server.
And as the next step, we will create a hibernate mapping file. This file defines how a Java class is mapped with the database table and acts like a bridge between Java types and database data types.

  • In the 'src' folder of your project directory, create an Event.hbm.xml file with the following content:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping> 
        <class name="com.dhtmlx.planner.DHXEvent" table="events">
                <id column="event_id" name="id" type="java.lang.Integer">
                        <generator class="increment"/>
                </id>
                <property column="start_date" name="start_date" type="timestamp"/>
                <property column="end_date" name="end_date" type="timestamp"/>
                <property column="event_name" name="text" type="java.lang.String"/>
        </class>
</hibernate-mapping>

Step 6. Configuring Hibernate

As Hibernate is not the subject of our tutorial we won’t detail using this library and assume that you know how to configure Hibernate.

If you’re not, please refer to the Hibernate documentation at http://www.hibernate.org/docs or check out the hibernate.cfg.xml file (demoapp_spring/src/hibernate.cfg.xml) in the supplied package.

Step 7. The HibernateUtil Helper Class

This helper class is required to get Hibernate up and running.

  • Create the com.dhtmlx.demoapp.controller package;
  • In the newly-created package, create a HibernateUtil.java file with the following code:
package com.dhtmlx.demoapp.controller;
 
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class HibernateUtil {
	private static final SessionFactory sessionFactory = buildSessionFactory();
	@SuppressWarnings("deprecation")
	private static SessionFactory buildSessionFactory() {
		try {
			return new Configuration().configure().buildSessionFactory();
		}
		catch (Throwable ex) {
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}
 
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}

Step 8. Loading and storing data

As Hibernate files for our application have been completed, it’s time to create a class that will handle all the Hibernate facilities. In JavaPlanner there is a special class for managing data, it’s DHXEventsManager. It defines logic for data loading and processing.

  • In the controller folder of your project directory, create a CustomEventsManager.java file and extend it from DHXEventsManager as in:
package com.dhtmlx.demoapp.controller;
 
import javax.servlet.http.HttpServletRequest;
import org.hibernate.Session;
 
 
import com.dhtmlx.planner.DHXStatus;
import com.dhtmlx.planner.DHXEv;
import com.dhtmlx.planner.DHXEventsManager;
 
import java.util.ArrayList;
import java.util.List;
 
public class CustomEventsManager extends DHXEventsManager {
 
	public CustomEventsManager(HttpServletRequest request) {
		super(request);
	}
 
	public Iterable<DHXEv> getEvents() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		List<DHXEv> evs = new ArrayList<DHXEv>();
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			evs = session.createCriteria(DHXEvent.class).list();
		} catch (RuntimeException e) {
			e.printStackTrace();
		} finally{
			session.flush();
			session.close();
		}
 
    	return evs;
	}
 
	@Override
	public DHXStatus saveEvent(DHXEv event, DHXStatus status) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
 
			if (status == DHXStatus.UPDATE)
				session.update(event);
			else if (status == DHXStatus.DELETE)
				session.delete(event);
			else if (status == DHXStatus.INSERT)
				session.save(event);
 
			session.getTransaction().commit();
		} catch (RuntimeException e) {
			e.printStackTrace();
		} finally{
			session.flush();
			session.close();
		}
		return status;
	}
 
	@Override
	public DHXEv createEvent(String id, DHXStatus status) {
		return new DHXEvent();
	}
}
  • getEvents() method answers for data loading;
  • saveEvent() method manages the update/insert/delete operations;
  • createEvent() method provide creating new events in the planer.

To learn more on loading and processing data in the planner, read:

Step 9. A controller file

Now, let’s create a controller class that will define actions for initializing the planner and loading data to it.

  • In the controller folder of your project directory, create a LoadingController.java file with the following code:
package com.dhtmlx.demoapp.controller;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
 
import com.dhtmlx.planner.DHXPlanner;
import com.dhtmlx.planner.DHXSkin;
import com.dhtmlx.planner.data.DHXDataFormat;
 
@Controller
public class LoadingController {
 
        @RequestMapping("/myplanner.html")
        public ModelAndView planner(HttpServletRequest request) throws Exception {
                DHXPlanner p = new DHXPlanner("./codebase/", DHXSkin.TERRACE);
                p.setInitialDate(2013, 1, 7);
                p.config.setScrollHour(music);
                p.setWidth(900);
                p.load("events", DHXDataFormat.JSON);
 
                ModelAndView mnv = new ModelAndView("article");
                mnv.addObject("body", p.render());
                return mnv;
        }
 
        @RequestMapping("/events")
        @ResponseBody public String events(HttpServletRequest request) {
                CustomEventsManager evs = new CustomEventsManager(request);
                return evs.run();
        }
}
  • In the initializing() function we use a standard code initializing JavaPlanner.
  • The events() function instantiates the CustomEventsManager class and retrieve data.

If you doubt what one or another method makes, refer to the following documentation:

Step 10. A view file

In the controller, we named our view file as ‘article’.

  • In the 'WebContent/WEB-INF/jsp' folder of your project directory, create an article.jsp file with the following code:
<html>
    <body>
        <div class="content" id="content">
           <div id="scheduler">${body}</div>
        </div>
    </body>
</html>



That’s it. Our tutorial came to the end. We have created an attractive planner application with the help of the Spring framework and JavaPlanner library. If you decide to continue developing and customize the application, this is a good point to start it. Good luck and see you soon!

All the related files you can download here.