Wednesday, February 8, 2012

Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 1)

In this tutorial, we will create a simple CRUD application using Spring 3.1 and Redis. We will based this tutorial on a previous guide for MongoDB: Spring MVC 3.1 - Implement CRUD with Spring Data MongoDB. This means we will re-use our existing design and implement only the data layer to use Redis as our data store.


Dependencies

  • Spring core 3.1.0.RELEASE
  • Spring Data Redis 1.0.0.RC1
  • Redis (server) 2.4.7
  • See pom.xml for details

Github

To access the source code, please visit the project's Github repository (click here)

Functional Specs

Before we start, let's define our application's specs as follows:
  • A CRUD page for managing users
  • Use AJAX to avoid page refresh
  • Users have roles: either admin or regular (default)
  • Everyone can create new users and edit existing ones
  • When editing, users can only edit first name, last name, and role fields
  • A username is assumed to be unique

Here's our Use Case diagram:
[User]-(View)
[User]-(Add) 
[User]-(Edit) 
[User]-(Delete) 

Database

If you're new to Redis and coming from a SQL-background, please take some time to read the Redis Official Documentation. I would like to put emphasis on studying the Redis data types. See Data types and A fifteen minute introduction to Redis data types.

In its purest form, Redis is a key-value store that can support various data structures: Strings, Sets, Lists, Hashes, and Sorted Sets. Among these structures, we will pay extra attention to Hashes because we can use it to represent Java objects.

Hashes

Redis Hashes are maps between string fields and string values, so they are the perfect data type to represent objects (eg: A User with a number of fields like name, surname, age, and so forth):

Source: Data types

From Java to Redis

We have two Java classes representing our domain: User and Role. Here is the Class diagram:

# Cool UML Diagram
[User|id;firstName;lastName;username;password;role{bg:orange}]1--1> [Role|id;role{bg:green}]

However, Redis is a key-value store, and we can already see the model mismatch. How do we exactly map a Java class to a Redis structure? One of way of dealing with this is to use Hash structure.

Assume we have the following User object with the following properties:
User
----
id = 1
username = john
password = 12345678
role = 1

To map this object to Redis, via the command-line tool, as a Hash structure we use the command HMSET:
redis> HMSET user:1 id 1 username john password 12345678 role 1
"OK"

redis> HGETALL user:1
{"id":"1","username":"john","password":"12345678","role":"1"}

In this example, user:1 becomes the column name and the id (if we think of this in terms of a relational database). Notice we don't have to map a Role object because we've already set the value along with the user key.

Try Redis

If you need to experiment with an actual Redis instance online, visit the Try Redis.


Screenshots

Let's preview how the application will look like after it's finished. This is also a good way to clarify further the application's specs. Note: These are the same screenshots you will see from the Spring MVC 3.1 - Implement CRUD with Spring Data MongoDB guide.

The Activity diagram:

http://yuml.me/diagram/activity/(start)-%3E%3Cd1%3Eview-%3E(Show%20Records)-%3E%7Ca%7C-%3E(end),%20%3Cd1%3Eadd-%3E(Show%20Form)-%3E%7Ca%7C,%20%3Cd1%3Eedit-%3E%3Cd2%3Ehas%20selected-%3E(Show%20Form)-%3E%7Ca%7C,%20%3Cd2%3Eno%20record%20selected-%3E(Popup%20Alert)-%3E%7Ca%7C,%20%3Cd1%3Edelete-%3E%3Cd3%3Ehas%20selected-%3E(Delete%20Record)-%3E%7Ca%7C,%20%3Cd3%3Eno%20record%20selected-%3E(Popup%20Alert)-%3E%7Ca%7C.

Entry page
The entry page is the primary page that users will see. It contains a table showing user records and four buttons for adding, editing, deleting, and reloading data. All interactions will happen in this page.

Entry page

Edit existing record
When user clicks the Edit button, an Edit Record form shall appear after the table.

Edit record form

When a user submits the form, a success or failure alert should appear.

Success alert

When the operation is successful, the update record should reflect on the table.

Edited record appears on the table

Create new record
When a user clicks the New button, a Create New Record form shall appear after the table.

Create new record form

When a user submits the form, a success or failure alert should appear.

Success alert

When the operation is successful, the new record should appear on the table.

New record shows on the form

Delete record
When user clicks the Delete button, a success or failure alert should appear.

Success alert

Reload record
When user clicks the Reload button, the data on the table should be reloaded.

Errors
When user clicks the Edit or Delete button without selecting a record first, a "Select a record first!" alert should appear.

Error alert

Next

In the next section, we will study how to setup a Redis server both in Windows and Ubuntu. Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 1) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 2)

Review

In the previous section, we have laid down the functional specs of the application and studied how to map a Java object to a Redis data structure. In this section, we will study how to setup a Redis server both in Windows and Ubuntu.


Redis Setup

We will demonstrate first how to setup Redis in Windows 7, then on Ubuntu 10.04.

Windows 7

To setup a Redis server in Windows, follow these steps:

1. Open a browser and visit the Redis download section at http://redis.io/download

2. Choose the Win32/64 download. Notice it's status is Unofficial because the Redis project does not directly support win32/win64


3. Although Windows is not officially supported, there's a port available for it by Dušan Majkić. Under the Win32/64 section, click on the link A Native win32/win64 port created by Dušan Majkić.. It will bring you to a Github page.

4. Click on the Downloads section (upper-right) and you should see the following downloads.


5. Download the latest one (currently, it's 2.4.5).

6. Once the download is finished, extract the contents. Open the new folder and browse under the 32bit folder (choose 64bit if you have Windows 64bit version).




7. To run a Redis server, double-click the redis-server.exe


You should see the following console stating that Redis is now running:


To run a client interface, double-click the redis-cli.exe


And you should see the following console--waiting for your command:


Ubuntu 10.04

To setup a Redis server in Ubuntu, you will need to build it from the source. There are two ways:
  • Manual download
  • Terminal-based

Manual download

1. Open a browser and visit the Redis download section at http://redis.io/download

2. Download the latest and stable version (currently at 2.4.7).

3. Once the download is finished, extract the contents.

4. Now, let's build the source. Open a terminal and enter the following command:
/REDIS-DOWNLOAD-PATH/make


After building Redis, test it using the following command (make sure to replace REDIS-DOWNLOAD-PATH accordingly):
/REDIS-DOWNLOAD-PATH/make test


5. The binaries that are now compiled are available in the src directory. Run Redis with:
/REDIS-DOWNLOAD-PATH/src/redis-server


Terminal-based

1. Download, extract and compile Redis with:
$ wget http://redis.googlecode.com/files/redis-2.4.7.tar.gz
$ tar xzf redis-2.4.7.tar.gz
$ cd redis-2.4.7
$ make


2. The binaries that are now compiled are available in the src directory. Run Redis with:
$ src/redis-server


Note: These are the same steps you will see under the Download section at http://redis.io/download

Next

In the next section, we will discuss the project's structure and start writing the Java classes. Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 2) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 3)

Review

In the previous section, we have learned how to setup a Redis server in Windows and Ubuntu. In this section, we will discuss the project's structure and write the Java classes.


Project Structure

Our application is a Maven project and therefore follows Maven structure. As we create the classes, we've organized them in logical layers: domain, repository, service, and controller.

Here's a preview of our project's structure:

Note: You might have noticed ignore an error icon in the jQuery file. This is an Eclipse validation issue. You can safely ignore this error.

The Layers

Domain Layer

This layer contains two POJOs, User and Role.




Controller Layer

This layer contains two controllers, MediatorController and UserController
  • MediatorController is responsible for redirecting requests to appropriate pages. This isn't really required but it's here for organizational purposes.
  • UserController is responsible for handling user-related requests such as adding and deleting of records



Service Layer

This layer contains two services, UserService and InitRedisService
  • UserService is our CRUD service for managing users
  • InitRedisService is used for initiliazing our database with sample data using the RedisTemplate



As mentioned in Part 1, we shall use Hashes to store Java objects in Redis. With the help of Spring Data for Redis, in particular the RedisTemplate, we're able to perform various Redis operations.

To access Hash operations using RedisTemplate, we use the following syntax:
template.opsForHash()
template.opsForHash().put
template.opsForHash().delete


To keep track of our users, we will use Set data structure for Redis
template.opsForSet()
template.opsForSet().add
template.opsForSet().remove


What is Spring Data Redis?

Spring Data for Redis is part of the umbrella Spring Data project which provides support for writing Redis applications. The Spring framework has always promoted a POJO programming model with a strong emphasis on portability and productivity. These values are carried over into Spring Data for Redis.

Source: http://www.springsource.org/spring-data/redis

Utility classes

TraceInterceptor class is an AOP-based utility class to help us debug our application. This is a subclass of CustomizableTraceInterceptor (see Spring Data JPA FAQ)



Next

In the next section, we will focus on the configuration files for enabling Spring MVC. Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 3) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 4)

Review

In the previous section, we have implemented the Java classes and discussed the Redis service. In this section, we will write the configuration files for enabling Spring MVC and Redis support.


Configuration

To enable Redis support, we need to declare the following beans
  • a Redis connection factory
  • a Redis template
  • Optionally, we declared an InitRedisService to automatically populate our database with sample data


Finally, here's our applicationContext.xml file

Next

In the next section, we will create the HTML and JavaScript files. Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 4) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 6)

Review

We have just completed our application! In the previous sections, we have discussed the functional specs, created the Java classes, declared the configuration files, and wrote the HTMl files. In this section, we will build and run the application using Maven, and show how to import the project in Eclipse.


Running the Application

Access the source code

To download the source code, please visit the project's Github repository (click here)

Preparing the data source

  1. Run Redis (see Part 2 for instructions)
  2. There's no need to populate the database with sample data because our InitRedisService will insert our sample data automatically

Building with Maven

  1. Ensure Maven is installed
  2. Open a command window (Windows) or a terminal (Linux/Mac)
  3. Run the following command:
    mvn tomcat:run
  4. You should see the following output:
    [INFO] Scanning for projects...
    [INFO] Searching repository for plugin with prefix: 'tomcat'.
    [INFO] artifact org.codehaus.mojo:tomcat-maven-plugin: checking for updates from central
    [INFO] artifact org.codehaus.mojo:tomcat-maven-plugin: checking for updates from snapshots
    [INFO] ------------------------------------------
    [INFO] Building spring-redis-tutorial Maven Webapp
    [INFO]    task-segment: [tomcat:run]
    [INFO] ------------------------------------------
    [INFO] Preparing tomcat:run
    [INFO] [apt:process {execution: default}]
    [INFO] [resources:resources {execution: default-resources}]
    [INFO] [tomcat:run {execution: default-cli}]
    [INFO] Running war on http://localhost:8080/spring-redis-tutorial
    Feb 8, 2012 8:57:04 PM org.apache.catalina.startup.Embedded start
    INFO: Starting tomcat server
    Feb 8, 2012 8:57:04 PM org.apache.catalina.core.StandardEngine start
    INFO: Starting Servlet Engine: Apache Tomcat/6.0.29
    Feb 8, 2012 8:57:05 PM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring root WebApplicationContext
    Feb 8, 2012 8:57:07 PM org.apache.coyote.http11.Http11Protocol init
    INFO: Initializing Coyote HTTP/1.1 on http-8080
    Feb 8, 2012 8:57:07 PM org.apache.coyote.http11.Http11Protocol start
    INFO: Starting Coyote HTTP/1.1 on http-8080
    
  5. Note: If the project will not build due to missing repositories, please enable the repositories section in the pom.xml!

Access the Entry page

  1. Follow the steps with Building with Maven
  2. Open a browser
  3. Enter the following URL (8080 is the default port for Tomcat):
    http://localhost:8080/spring-redis-tutorial/

Import the project in Eclipse

  1. Ensure Maven is installed
  2. Open a command window (Windows) or a terminal (Linux/Mac)
  3. Run the following command:
    mvn eclipse:eclipse -Dwtpversion=2.0
  4. You should see the following output:
    [INFO] Scanning for projects...
    [INFO] Searching repository for plugin with prefix: 'eclipse'.
    [INFO] org.apache.maven.plugins: checking for updates from central
    [INFO] org.apache.maven.plugins: checking for updates from snapshots
    [INFO] org.codehaus.mojo: checking for updates from central
    [INFO] org.codehaus.mojo: checking for updates from snapshots
    [INFO] artifact org.apache.maven.plugins:maven-eclipse-plugin: checking for updates from central
    [INFO] artifact org.apache.maven.plugins:maven-eclipse-plugin: checking for updates from snapshots
    [INFO] -----------------------------------------
    [INFO] Building spring-redis-tutorial Maven Webapp
    [INFO]    task-segment: [eclipse:eclipse]
    [INFO] -----------------------------------------
    [INFO] Preparing eclipse:eclipse
    [INFO] No goals needed for project - skipping
    [INFO] [eclipse:eclipse {execution: default-cli}]
    [INFO] Adding support for WTP version 2.0.
    [INFO] -----------------------------------------
    [INFO] BUILD SUCCESSFUL
    [INFO] -----------------------------------------
    
    This command will add the following files to your project:
    .classpath
    .project
    .settings
    target
    You may have to enable "show hidden files" in your file explorer to view them
  5. Open Eclipse and import the project

Conclusion

That's it! We've have successfully completed our Spring MVC 3.1 web application. We've learned how to setup Redis and access it through Spring Data Redis. Furthermore, we used AJAX to make the application responsive.

I hope you've enjoyed this tutorial. Don't forget to check my other tutorials at the Tutorials section.

Revision History


Revision Date Description
1 Feb 8 2012 Uploaded tutorial and Github repository

StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 6) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share

Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 5)

Review

In the previous section, we have created the configuration files and discussed them accordingly. In this section, we will focus on the view layer, in particular the HTML files and JavaScript codes.


HTML Files (with AJAX)

To improve the user experience, we will use AJAX to make the application responsive. All actions will be performed on the same page (no page refresh). Consequently, we only have one HTML page for the entire application. The rest are JavaScript files.

Notice how we've structured the HTML page. Basically, we followed the concept of separation of concerns by separating markup tags, CSS, and JavaScript code. We tried as much as possible to make the JavaScript code and CSS styles unobtrusive.



A Closer Look

At first glance, this JSP file seems complex. On the contrary, it's quite simple. Let's break it into smaller pieces for clarity:

URLs
The following declares our URLs as mapped to our UserController. We're using the url taglib to make the URL portable.


Imports
Here we're importing custom CSS and JavaScript files, along with jQuery.


What is jQuery?
jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.

Source: http://jquery.com/

JavaScript initialization
Here we're preparing the URLs, attaching functions to our buttons, and initially loading the table. The main chunk of the JavaScript code is referenced from an external JavaScript file custom.js
  • loadTable(): Performs an AJAX request and populates our table with records
  • toggleForms(): Hides and shows specific forms based on the passed argument
  • toggleCrudButtons(): Hides and shows buttons
  • hasSelected(): Checks whether a record has been selected
  • fillEditForm(): Fills the Edit form with details based on the selected record
  • submitDeleteRecord(): Submits a delete request via AJAX
  • submitNewRecord(): Submits a create new record request via AJAX
  • submitUpdateRecord(): Submits an update record request via AJAX


Table and buttons
This is a simple table for displaying records. The buttons are for interacting with the data.


Forms
These are forms used when adding and editing records.


Preview

If we run our application, this is what we shall see:

Entry page

For more screenshots, please visit Part 1 of this tutorial and check the Screenshots section.

Next

In the next section, we will build and run the application using Maven, and show how to import the project in Eclipse. Click here to proceed.
StumpleUpon DiggIt! Del.icio.us Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring MVC 3.1 - Implement CRUD with Spring Data Redis (Part 5) ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share